← 中文资源

简体中文版本

forEach 里的 await 不会等待

forEach 会直接丢弃回调返回的 promise:调用方同步返回、完成计数停在 0;逐个等待用 for...of,真要并发就显式收集 promise 再 Promise.all。

阅读英文原文

实现说明

真正干活的是函数 notifyBroken、notifySequential、notifyParallel,其余都是接线。 迭代发生在 for (const item of items) 内部——循环之外的语句只执行一遍。每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。

使用要点

  • 每一步打印都带着自己的标签:processed:、forEach returned, done =、sequential:。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 文件在加载时定义 notifyBroken、notifySequential、notifyParallel。

入口签名:async function notifyBroken(items)

核心语句

await new Promise((resolve) => setTimeout(resolve, 15));
await new Promise((resolve) => setTimeout(resolve, 10));
await new Promise((resolve) => setTimeout(resolve, 20));

代码示例

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');