Await map Items Are Promises Not Values
Contrast sequential awaits with ordered parallel completion: map launches every call immediately and yields promises you await by index later.
Code
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));Output
Captured from a sandboxed run of this snippet in the build pipeline.
disk ready
net ready
clock ready
0 disk ready
1 net ready
2 clock ready
map items are promises: trueHow the snippet works
Await map Items Are Promises Not Values keeps everything in the function probe.
Two loops stack here: for (const unit of ['disk', 'net', 'clock']) selects, for (const [index, pending] of inFlight.entries()) processes. The async parts await their results, which keeps ordering predictable.
Applying it
Entry signature: async function probe(unit)
Running the file prints labeled results such as map items are promises: — each operation’s effect is visible in the output.
Statements that matter
await new Promise((resolve) => setTimeout(resolve, 10));
const inFlight = units.map((unit) => probe(unit));
const mapped = units.map((unit) => probe(unit));
FAQ
- Is anything beyond the standard library required?
- Nothing beyond the standard library — the snippet is dependency-free. The file defines `probe` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.