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

后端 未结 5 546
谎友^
谎友^ 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:09

    It's a great chance to start using jQuery Deferred.

    Apart from the callbacks-based solution the code is readable, flexible and highly maintainable

    http://jsfiddle.net/zerkms/zJhph/

    function firstFunction(){
      var d = $.Deferred();
      // some very time consuming asynchronous code...
      setTimeout(function() {
        console.log('1');
        d.resolve();
      }, 1000);
      return d.promise();
    }
    function thirdFunction(){
      var d = $.Deferred();
      // definitely dont wanna do this until secondFunction is finished
      setTimeout(function() {
        console.log('3');
        d.resolve();
      }, 1000);
      return d.promise();
    }
    function secondFunction(){
      var d = $.Deferred();
      setTimeout(function() {
        console.log('2');
        d.resolve();
      }, 1000);
      return d.promise();
    }
    function fourthFunction(){
      var d = $.Deferred();
      // last function, not executed until the other 3 are done.
      setTimeout(function() {
        console.log('4');
        d.resolve();
      }, 1000);
      return d.promise();
    }
    
    firstFunction().pipe(secondFunction).pipe(thirdFunction).pipe(fourthFunction);​
    

    PS: as an example of asynchronous code I've used setTimeout. The main thing is that in the end of the asynchronous part you need to call d.resolve() to continue chaining methods.

    Further reading: http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

提交回复
热议问题