sequencing function calls in javascript - are callbacks the only way?

后端 未结 5 548
谎友^
谎友^ 2021-02-03 11:25

I read through various threads like this one for example.

But it really escapes me how to accomplish the following:

I have 4 functions, and want them happen one

5条回答
  •  一向
    一向 (楼主)
    2021-02-03 12:16

    The idea is you'd do something like the following so that once the first function was done running, it'd know what to run as opposed to you having to figure it out on your own outside the function:

    function firstFunction(callback){
      // some very time consuming asynchronous code...
      console.log('1');
    
      return callback(function(){
        alert("Second function finished.");
        return true;
      });
    }
    function secondFunction(callback){
      // waits for firstFunction to be completed
      console.log('2');
    
      return callback();
    }
    
    firstFunction(secondFunction);
    

    Also look up .apply() and .call().

提交回复
热议问题