How to execute a Javascript function only after multiple other functions have completed?

后端 未结 7 2039
轻奢々
轻奢々 2020-12-25 15:03

My specific problem is that I need to execute a (potentially) large number of Javascript functions to prepare something like a batch file (each function call adds some infor

7条回答
  •  爱一瞬间的悲伤
    2020-12-25 15:50

    If you want to keep it simple, you can use a counter-based callbacks system. Here's a draft of a system that allows when(A, B).then(C) syntax. (when/then is actually just sugar, but then again the whole system arguably is.)

    var when = function() {
      var args = arguments;  // the functions to execute first
      return {
        then: function(done) {
          var counter = 0;
          for(var i = 0; i < args.length; i++) {
            // call each function with a function to call on done
            args[i](function() {
              counter++;
              if(counter === args.length) {  // all functions have notified they're done
                done();
              }
            });
          }
        }
      };
    };
    

    Usage:

    when(
      function(done) {
        // do things
        done();
      },
      function(done) {
        // do things
        setTimeout(done, 1000);
      },
      ...
    ).then(function() {
      // all are done
    });
    

提交回复
热议问题