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