For await Handles Promise Results One At A Time

for await over already-started promises handles each result one at a time in start order; await inside the loop body serializes the starts as well.

JavascriptResilience

Code

javascriptsnippet
34 lines
const sleep = (label, ms) =>
  new Promise((resolve) => setTimeout(() => resolve(label), ms));

const specs = [
  ['a', 60],
  ['b', 20],
  ['c', 40],
];

// ① 先启动、for await 逐个处理:执行并发,处理按启动顺序一次一个
const jobs = specs.map(([label, ms]) => sleep(label, ms));
let t0 = Date.now();
const handled = [];
for await (const label of jobs) {
  handled.push(label);
}
const handledMs = Date.now() - t0;
console.log('started first, for await:', handled.join(' -> '), handledMs + 'ms');

// ② await 写在循环体里:连启动都串行,总时长接近各段之和
t0 = Date.now();
const serial = [];
for (const [label, ms] of specs) {
  serial.push(await sleep(label, ms));
}
const serialMs = Date.now() - t0;
console.log('await inside the loop   :', serial.join(' -> '), serialMs + 'ms');

// ③ Promise.all 等全部任务,一次拿到按启动顺序排列的结果
t0 = Date.now();
const all = await Promise.all(specs.map(([label, ms]) => sleep(label, ms)));
console.log('Promise.all             :', all.join(' -> '), (Date.now() - t0) + 'ms');

console.log('started-first stays near the slowest task, in-loop awaits pay every delay:', handledMs, 'vs', serialMs);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

started first, for await: a -> b -> c 75ms
await inside the loop   : a -> b -> c 149ms
Promise.all             : a -> b -> c 63ms
started-first stays near the slowest task, in-loop awaits pay every delay: 75 vs 149

Inside the snippet

Count the function sleep as the entire surface area of For await Handles Promise Results One At A Time.

Iteration is nested: for await (const label of jobs) frames the pass, for (const [label, ms] of specs) does the per-item step. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Putting it to use

The main signature reads const sleep = (label, ms)

Output lines are prefixed (started first, for await:, await inside the loop :, Promise.all :), making each step’s effect easy to spot.

Core lines

const all = await Promise.all(specs.map(([label, ms]) => sleep(label, ms)));
new Promise((resolve) => setTimeout(() => resolve(label), ms));
const jobs = specs.map(([label, ms]) => sleep(label, ms));

Interactive Tools for This Topic

FAQ

Does the runtime need any help from npm, pip, cargo, or the like?
No — the package manager has nothing to do here; nothing is declared. The file defines `sleep` at load time.