How to sync JavaScript callbacks?

前端 未结 6 1395
长发绾君心
长发绾君心 2020-12-01 08:54

I\'ve been developing in JavaScript for quite some time but net yet a cowboy developer, as one of the many things that always haunts me is synching JavaScript\'s callbacks.<

6条回答
  •  隐瞒了意图╮
    2020-12-01 09:13

    With this helper function:

    function afterAll(callback,what) {
      what.counter = (what.counter || 0) + 1;
      return function() {
        callback(); 
        if(--what.counter == 0) 
          what();
      };
    }
    

    your loop will look like this:

    function whenAllDone() { ... }
    for (... in ...) {
      myFunc1(afterAll(callback,whenAllDone)); 
    }
    

    here afterAll creates proxy function for the callback, it also decrements the counter. And calls whenAllDone function when all callbacks are complete.

提交回复
热议问题