How to add a callback to a function in javascript

2020-02-08 12:04发布

I have two javascript functions

function one () {
   do something long... like writing jpgfile on disk
}

function two () {
   do something fast... like show the file
}

I call it (in jQuery) like this

 one ();
 two ();

Because function two needs the link file from function one, i need to be sure the execution is completed... so getting the function two in the callback of function one should be the trick.. but how to do that ?

note : I did put an alert ('aaa') between those two functions to let function one complete, and it worked fine... when the alert is commented (removed) nothing works anymore !

4条回答
家丑人穷心不美
2楼-- · 2020-02-08 12:48

Simple:

function one (callback) {
   do something long... like writing jpgfile on disk

    if(callback) callback();
}

function two () {
   do something fast... like show the file
}

one(two);
查看更多
走好不送
3楼-- · 2020-02-08 12:49

Try this,

$.when($.ajax(fuction1())).then(function () {

fuction2;

});

Here fuction1 is your first function to call, and fuction2 is your second function.

查看更多
Explosion°爆炸
4楼-- · 2020-02-08 12:55

I think it's easy if the browser wait for the process inside "one()" to be done before execute the next line of command. The iceberg hit titanic cause it doesn't wait. Then executing this:

one(two) // while two is the callBack parameter

is nothing different from:

one()
two()

I suggest using a setInterval.

function one(){
    //--- Write the file to disk
    //.....................
}

function runTwo(){
    if (check_the_written_file_existence){
         clearInterval(t)
         two();
    }
}
var t = setInterval("runTwo()",500)

The most important point is that if there's an event fires when the "long process" in function "one()" has done, you just need to bind function two to that event. Unless, you must check the result by someway every span of time until it's really done.

查看更多
疯言疯语
5楼-- · 2020-02-08 12:57

You only need to use a callback if you are doing something asynchronous, otherwise it doesn't matter how long something takes, the next function won't run until the first has finished.

A callback is just passing a function as an argument, and then calling it when done.

function one (callback) {
   do something long... like writing jpgfile on disk
   callback();
}

function two () {
   do something fast... like show the file
}

one(two);

Obviously, if you are doing something asynchronous, then you need something that will tell you when it is finished (such as an event firing).

查看更多
登录 后发表回答