How do I know when an asynchronous loop is running?

I have a for loop that runs hundreds of asynchronous functions. Once all the functions are complete, I need to run one last function, but I canโ€™t deceive it, knowing when all the functions will be completed.

I tried promises, but as soon as any of the functions in the loop is resolved, my promise function will end.

for(var i = 0; i < someArray.length; i ++){ // these can take up to two seconds and have hundreds in the array asyncFunction(someArray[i]; } 

How can I tell as soon as each function is completed?

+4
source share
3 answers

Increment

You can add a callback that grows:

 for (var i = 0; i < len; i++) { asycFunction(someArray[i]); asycFunction.done = function () { if (i == someArray.length - 1) { // Done with all stuff } }; } 

Recursive approach

This type of approach is preferred by some developers, but (possibly) takes longer because it is waiting for completion to start another.

 var limit = someArray.length, i = 0; function do(i) { asyncFunction(someArray[i]); asyncFunction.done = function () [ if (i++ == someArray[i]) { // All done! } else { do(i); } } } do(i++); 

Promises

Promises are not yet supported, but you can use the library. However, this will add a little to your page.


Good decision

 (function (f,i) { do(i++,f) }(function (f,i) { asyncFunction(someArray[i]); asyncFunction.done = function () { if (i++ === someArray.length - 1) { // Done } else { f(i) } }; }, 0) 
+4
source

Many libraries have .all resolver:

You can use them or find out their source code.

Assuming the code is the body of the foo() function:

 function foo() { return Promise.all(someArray.map(function(item) { //other stuff here return asyncFunction(item, /* other params here */); })); } 

Or, if there is no other material, and no other parameters pass:

 function foo() { return Promise.all(someArray.map(asyncFunction)); } 
+3
source

You can check the number of responses.

For each answer, you can increase the counter value, and if the counter value matches the value of someArray.length, you can assume that all Async functions are complete and can start the next step.

+1
source

All Articles