Await Inside Foreach Does Not Wait
Show that forEach ignores awaited callbacks and the caller returns before work finishes, then fix it with for...of or an explicit Promise.all collection.
Code
const tasks = ['resize', 'watermark', 'upload'];
// forEach 会直接丢弃回调返回的 promise:notify 同步返回,"全部完成"的断言为假
async function notifyBroken(items) {
let done = 0;
items.forEach(async (item) => {
await new Promise((resolve) => setTimeout(resolve, 15));
done += 1;
console.log('processed:', item);
});
console.log('forEach returned, done =', done);
}
async function notifySequential(items) {
for (const item of items) {
await new Promise((resolve) => setTimeout(resolve, 5));
console.log('sequential:', item);
}
return items.length;
}
async function notifyParallel(items) {
const pending = items.map(async (item) => {
await new Promise((resolve) => setTimeout(resolve, 10));
console.log('parallel:', item);
});
await Promise.all(pending);
}
await notifyBroken(tasks);
// 等被丢弃的回调落地,保证示例输出稳定(真实代码里没人替你等)
await new Promise((resolve) => setTimeout(resolve, 20));
console.log('---');
console.log('sequential count:', await notifySequential(tasks));
await notifyParallel(tasks);
console.log('all parallel done');How the snippet works
The working surface is the functions notifyBroken, notifySequential and notifyParallel — everything else is wiring.
The one repetition in this snippet is the loop for (const item of items). Every asynchronous step is awaited, so rejections surface where the call happens.
Applying it
The primary signature is async function notifyBroken(items)
The run emits 7 labeled sections — processed:, forEach returned, done =, sequential:, parallel:, ---, sequential count:, all parallel done — one per step.
Statements that matter
await new Promise((resolve) => setTimeout(resolve, 15));
await new Promise((resolve) => setTimeout(resolve, 10));
await new Promise((resolve) => setTimeout(resolve, 20));
Interactive Tools for This Topic
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `notifyBroken`, `notifySequential`, `notifyParallel` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.