Callback after all asynchronous forEach callbacks are completed

后端 未结 13 2318
谎友^
谎友^ 2020-11-22 12:56

As the title suggests. How do I do this?

I want to call whenAllDone() after the forEach-loop has gone through each element and done some asynchronous p

13条回答
  •  情书的邮戳
    2020-11-22 13:28

    Hope this will fix your problem, i usually work with this when i need to execute forEach with asynchronous tasks inside.

    foo = [a,b,c,d];
    waiting = foo.length;
    foo.forEach(function(entry){
          doAsynchronousFunction(entry,finish) //call finish after each entry
    }
    function finish(){
          waiting--;
          if (waiting==0) {
              //do your Job intended to be done after forEach is completed
          } 
    }
    

    with

    function doAsynchronousFunction(entry,callback){
           //asynchronousjob with entry
           callback();
    }
    

提交回复
热议问题