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.
Using return in a forEach() is equivalent to a continue in a conventional loop.
'return' doesn't stop looping The reason is that we are passing a callback function in our forEach function, which behaves just like a normal function and is applied to each element no matter if we return from one i.e. when element is 2 in our case.
forEach() calls a provided callbackFn function once for each element in an array in ascending index order.
forEach loop is not asynchronous. The Array. prototype. forEach method accepts a callback as an argument which can be an asynchronous function, but the forEach method will not wait for any promises to be resolved before moving onto the next iteration.
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
}
});
});
Try this :
myArray.forEach(function(element, index, array){
asynchronous(function(data){
if (index === myArray.length - 1) {
response.push(data);
functionAfterForEach();
}
})
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With