According to JavaScript, Node.js: is Array.forEach asynchronous?, Array.forEach is synchronous. However, for my code below:
function wait5() {
return new Promise(resolve =>
setTimeout(resolve, 5000));
}
async function main() {
console.log("Start");
[1,2].forEach(async (e) => {
const d = await wait5().then(()=> console.log("5s later") )
})
console.log("This should come last!");
}
main();
The output is:
Start
This should come last!
5s later
5s later
with the two "5s later" coming out in rapid succession.
Why is this the case?
If I use a normal for loop:
async function main() {
console.log("Start");
for (let i=0;i<2;i++) {
const d = await wait5().then(()=> console.log("5s later") )
}
console.log("This should come last!");
}
then the result is what I wanted:
Start
5s later
5s later
This should come last!
.forEach()mechanism on its own performs no asynchronous work. The same cannot be said for code that's passed in as the callback, which is free to do anything it wants.awaitis the key here.forEachand everything to do with[1,2].forEach(async (e) =>where you declared the callback toforEachto beasync..forEach()callback.