Callback after all asynchronous forEach callbacks are completed

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

    var i=0;
    const waitFor = (ms) => 
    { 
      new Promise((r) => 
      {
       setTimeout(function () {
       console.log('timeout completed: ',ms,' : ',i); 
         i++;
         if(i==data.length){
          console.log('Done')  
        }
      }, ms); 
     })
    }
    var data=[1000, 200, 500];
    data.forEach((num) => {
      waitFor(num)
    })
    

提交回复
热议问题