I'm trying to execute a function after a forEach loop has completed all iterations.
This answer provides an interesting solution, but I can't get it to work.
Here's the code I adapted, creating a simple asyncFunction().
function callback () { console.log('all done'); }
function asyncFunction(item) {
console.log("in async function, item is " + item)
}
var itemsProcessed = 0;
[1, 2, 3].forEach((item, index, array) => {
asyncFunction(item, () => {
itemsProcessed++;
console.log("in callback area, itemsProcessed is " + itemsProcessed )
if(itemsProcessed === array.length) {
callback();
}
});
});
As visible in this JSfiddle, the script correctly executes the async function, but fails to enter the part which increments itemsProcessed
and should trigger the callback()
function.
I'm not too familiar with the fat arrow functions, so maybe the error comes from their usage.
Can anyone explain why the script isn't behaving as expected?
asyncFunction()
when you call it but function declaration doesn't expect second argument and never calls the callback passed to it – charlietflasyncFunction(item, ())
doesn't work. Could you please explain more explicitly how to tackle this second argument? – sc28