实现说明
底层就是函数 probe。
这里叠了两层循环:for (const unit of ['disk', 'net', 'clock']) 负责挑选,for (const [index, pending] of inFlight.entries()) 负责处理。异步部分依次 await 结果,顺序可预测。
使用要点
- 每一步打印都带着自己的标签:
map items are promises:。
常见问题
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。 文件在加载时定义 probe。
主签名形如 async function probe(unit)
核心语句
await new Promise((resolve) => setTimeout(resolve, 10));
const inFlight = units.map((unit) => probe(unit));
const mapped = units.map((unit) => probe(unit));
代码示例
async function probe(unit) {
await new Promise((resolve) => setTimeout(resolve, 10));
return unit + ' ready';
}
// 顺序执行:每个 await 等上一步完成,输出次序确定
for (const unit of ['disk', 'net', 'clock']) {
const message = await probe(unit);
console.log(message);
}
// 保留顺序的并行:先发射全部任务,再按原始下标 await
const units = ['disk', 'net', 'clock'];
const inFlight = units.map((unit) => probe(unit));
for (const [index, pending] of inFlight.entries()) {
console.log(index, await pending);
}
// 语义对照:map 的回调拿到的是 promise,不是等待后的值
const mapped = units.map((unit) => probe(unit));
console.log('map items are promises:', mapped.every((p) => p instanceof Promise));