← 中文资源

简体中文版本

async map 收集的是 Promise 数组

map 配 async 回调收集到的是 Promise 数组而非结果值:Promise.all 等齐并发请求,for..of 里逐个 await 则串行执行,两种顺序语义要分清。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

map collects promises: true
mapped[i].plan is undefined: true
awaited: a1:pro | b2:free | c3:free
sequential count: 3

实现说明

真正干活的是函数 sleep、fetchProfile、main,其余都是接线。 for (const id of ids) sequential.push(await fetchProfile(id)); 是唯一的迭代点——其余代码顺序执行一遍。await 点把异步工作排成序列,拒绝落在取结果的那一行。 返回值是携带 id 的对象。

使用要点

  • 跑完文件,输出里会留下标记——map collects promises:、mapped[i].plan is undefined:、awaited:。
  • main 按顺序串起 fetchProfile;运行文件就会把这个流程跑一遍。

常见问题

sleep 会修改传入的参数吗?

入参保持不变;拿回来的是新建的值。

运行「async map 收集的是 Promise 数组」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 map collects promises:、mapped[i].plan is undefined:、awaited: 标签标明各步骤。

主签名形如 const sleep = (ms)

核心语句

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const profiles = await Promise.all(mapped);
for (const id of ids) sequential.push(await fetchProfile(id));

代码示例

// Array.prototype.map returns synchronously: with an async callback you collect Promises,
// not values - you must await them all before you actually have the data
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

const fetchProfile = async (id) => {
  await sleep(20);
  return { id, plan: id.startsWith('a') ? 'pro' : 'free' };
};

async function main() {
  const ids = ['a1', 'b2', 'c3'];

  const mapped = ids.map((id) => fetchProfile(id));
  console.log('map collects promises:', mapped.every((v) => v instanceof Promise));
  console.log('mapped[i].plan is undefined:', mapped[0].plan === undefined);

  // Promise.all waits for all three: the requests already fired concurrently during map
  const profiles = await Promise.all(mapped);
  console.log('awaited:', profiles.map((p) => `${p.id}:${p.plan}`).join(' | '));

  // Sequential alternative: await one by one in for...of - each starts only after the previous finishes
  const sequential = [];
  for (const id of ids) sequential.push(await fetchProfile(id));
  console.log('sequential count:', sequential.length);
}

main();