forEach Ignores Async Callbacks
forEach calls async callbacks without awaiting them, so the loop ends before the work does; for...of awaits sequentially and Promise.all waits in parallel.
Code
function tick(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// forEach 不等待 async 回调:循环立即走完,done 还是空
const started = [];
const done = [];
[1, 2, 3].forEach(async (n) => {
started.push(`start ${n}`);
await tick(30);
done.push(`done ${n}`);
});
console.log("after forEach: started =", started.length, "done =", done.length);
async function main() {
// 修正一:for...of 逐个 await(顺序执行)
const seq = [];
for (const n of [1, 2, 3]) {
await tick(5);
seq.push(n);
}
console.log("for-of seq :", seq.join(","));
// 修正二:Promise.all 并行等全部完成
const parallel = await Promise.all(
[1, 2, 3].map(async (n) => {
await tick(5);
return n * 10;
}),
);
console.log("Promise.all :", parallel.join(","));
// 等 forEach 的回调全部落地(30ms 后必完成)
await tick(40);
console.log("forEach late :", done.sort().join(","));
}
main();Output
Captured from a sandboxed run of this snippet in the build pipeline.
after forEach: started = 3 done = 0
for-of seq : 1,2,3
Promise.all : 10,20,30
forEach late : done 1,done 2,done 3What the code does
The snippet is organized around the functions tick and main.
A single loop drives the file — for (const n of [1, 2, 3]). Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
The result is a fresh construction, so callers can keep their originals.
Applying it
Entry signature: function tick(ms)
The file announces its steps in the output: after forEach: started =, for-of seq :, Promise.all :.
Launch the file; main takes over and steps through tick.
Statements that matter
return new Promise((resolve) => setTimeout(resolve, ms));
const parallel = await Promise.all(
[1, 2, 3].map(async (n) => {
await tick(5);
return n * 10;
}),
);
[1, 2, 3].forEach(async (n) => {
started.push(`start ${n}`);
await tick(30);
done.push(`done ${n}`);
});
Interactive Tools for This Topic
FAQ
- Does `tick` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- What does forEach Ignores Async Callbacks print when run?
- Running the file directly is enough — expect labeled output lines such as `after forEach: started =`, `forEach late :`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.