Front response at completion

I want to call back when the foreach finished, but it does not work properly. How can i do this?

 var response = []; myArray.forEach(function(data) { data.asyncFunction(function(result) { response.push(result); }); }, function() { console.log(response); // Not being called. }); console.log(response); // (Empty) Executed before foreach finish. 
+5
source share
2 answers

Because forEach accepts only one callback . Since you are calling the asynchronous method inside forEach , you need to check if the whole asyn call has completed

 var response = []; myArray.forEach(function(data, index) { data.asyncFunction(function(result) { response.push(result); if(response.length === myArray.length) { //foreach work done } }); }); 
+5
source

Try the following:

 myArray.forEach(function(element, index, array){ asynchronous(function(data){ if (index === myArray.length - 1) { response.push(data); functionAfterForEach(); } }) }); 
+3
source

All Articles