Thursday, September 5, 2019

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

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...