Sunday, 23 July 2017

javascript - Foreach callback when finish




I want to execute a callback when foreach has finished, but it's not working properly.How can I do that?



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.

Answer



Because forEach accept only one callback. Since you are calling asynchronous method inside forEach you need to check whether all asyn call completed



var response = [];

myArray.forEach(function(data, index) {
data.asyncFunction(function(result) {
response.push(result);
if(response.length === myArray.length) {
//foreach work done
}
});
});

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...