Saturday 23 November 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...