Sub topic 9
Sequential Loops versus Concurrent Work
This chapter assumes you know how for await...of consumes async iterables, how it handles plain arrays of promises, and how try/catch catches errors raised during iteration. You should also be comfortable with Promise.all.
for await...of handles one value at a time. It asks for the next value, waits for it, runs the loop body, and only then asks again. That order is useful when each step depends on the one before it. When the tasks are independent, the same order wastes time.
The working model
A loop that awaits inside its body runs the tasks one after another, so the total time is the sum of every task's duration. Starting all the tasks first and then waiting for them together makes the total time roughly equal to the slowest task.
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function sequential() {
const results = [];
for (const ms of [300, 200, 100]) {
results.push(await sleep(ms, ms)); // about 600 ms total
}
return results;
}
async function concurrent() {
// all timers start at once, about 300 ms total
return Promise.all([300, 200, 100].map((ms) => sleep(ms, ms)));
}
async function main() {
let start = Date.now();
console.log(await sequential(), `${Date.now() - start} ms`);
start = Date.now();
console.log(await concurrent(), `${Date.now() - start} ms`);
}
main();
// [ 300, 200, 100 ] ~600 ms
// [ 300, 200, 100 ] ~300 msBoth functions return results in input order. The only difference is when each task starts. In sequential, the next timer is not created until the previous await finishes. In concurrent, map creates all three promises right away.
Choosing between them
| Situation | Prefer |
|---|---|
| Each step needs the previous result (pagination cursors, ordered writes) | Sequential `for await...of` |
| The source produces values over time (streams, events) | Sequential `for await...of` |
| Independent tasks whose inputs you already know (fetch 20 URLs) | `Promise.all` |
| Independent tasks where you need every outcome, even failures | `Promise.allSettled` |
| Many tasks and a server or resource that limits load | Batches or a concurrency limit |
Failure behaves differently in each approach. Promise.all rejects as soon as any one task rejects. The other tasks keep running, but you lose their results. A sequential loop stops at the first failure, and the later tasks never start. Use Promise.allSettled when you need a report of every success and every failure.
Common error: looping over already-started promises
Passing an array of promises to for await...of looks sequential, but it is not. The promises already started when the array was built. The loop only reads the results in order.
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
const tasks = [sleep(300, 'a'), sleep(100, 'b')]; // both running now
for await (const v of tasks) {
console.log(v); // 'a' at ~300 ms, then 'b' immediately
}
}
main();A middle ground: batches
When you have hundreds of tasks, running them all at once can overload an API. Processing them in fixed-size chunks runs each chunk concurrently while the chunks themselves run in sequence:
async function inBatches(items, size, worker) {
const results = [];
for (let i = 0; i < items.length; i += size) {
const chunk = items.slice(i, i + size);
results.push(...(await Promise.all(chunk.map(worker))));
}
return results;
}
inBatches([1, 2, 3, 4, 5], 2, async (n) => n * 10).then(console.log);
// [ 10, 20, 30, 40, 50 ]Each batch waits for its slowest task. A worker pool that starts a new task as soon as any slot frees up keeps throughput higher, but it takes more code to write.
Exercise
A loop runs for (const id of ids) { users.push(await getUser(id)); } over 50 ids, and each call takes about 200 ms. Roughly how long does it take, and how would you rewrite it if the calls are independent?
Show answer
About 10 seconds (50 × 200 ms), because each call starts only after the previous one finishes. If the calls are independent, write const users = await Promise.all(ids.map(getUser));, which takes about 200 ms. If the server limits load, process the ids in batches instead.
Exercise
Why can for await (const r of [fetchA(), fetchB()]) crash Node.js even inside a try/catch?
Show answer
Both promises start when the array is built. If fetchB() rejects while the loop is still awaiting fetchA(), no handler is attached to fetchB()'s promise yet, so Node.js reports an unhandled rejection. Promise.all attaches handlers to every promise right away.