Sub topic 9
Sequential Loops versus Concurrent Work
This chapter assumes you are comfortable with promises, async/await, Promise.all, and the for await...of loop from earlier chapters. You should also know that for await...of can loop over an array of promises. Here the question is timing. When you write a loop that awaits, how long does the whole job take, and when should you use a different pattern?
Why for await...of Is Always Sequential
A for await...of loop works in a fixed order. It calls next() on the iterator and awaits the result. Then it runs the loop body, and if the body contains await, it waits for that too. Only after that does it call next() again. The loop never asks for item two while item one is still in progress.
This is deliberate. Async iteration models a stream of values that arrive over time, such as lines from a file, pages from an API, or messages from a socket. For those sources, order matters. Asking for the next value before you have dealt with the current one would also defeat backpressure. Backpressure means the consumer controls how fast the producer runs.
The same holds for a plain for...of loop with await in its body. In both cases the time per item adds up:
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 time(label, fn) {
const start = Date.now();
const result = await fn();
console.log(label, result, `${Date.now() - start} ms`);
}
async function main() {
await time('sequential', sequential); // [300, 200, 100] ~600 ms
await time('concurrent', concurrent); // [300, 200, 100] ~300 ms
}
main();Both versions return the results in the same order. The sequential version takes the sum of all delays. The concurrent version takes only as long as the slowest delay. Promise.all keeps results in input order no matter which promise settles first.
When Work Starts: The Real Rule
What matters is when each promise is created, not which loop syntax you use. A promise-returning function starts its work as soon as you call it. await only waits for work that is already running. So:
for (const x of items) await work(x)creates each promise inside the loop, one at a time. This is sequential.items.map(work)creates every promise right away. This is concurrent, whatever you do with the promises afterwards.
That is why for await...of over an array of already-created promises behaves differently from a loop that awaits inside its body:
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
const start = Date.now();
const promises = [300, 200, 100].map((ms) => sleep(ms, ms)); // all started
for await (const value of promises) {
console.log(value, `${Date.now() - start} ms`);
}
}
main();
// 300 ~300 ms
// 200 ~300 ms
// 100 ~300 msAll three timers run at the same time. The loop still hands you the values in array order, so the 100 ms result waits behind the 300 ms one. The total time is about 300 ms, but the first value only arrives after 300 ms.
Choosing a Promise Combinator
When the work can run concurrently, pick the combinator that matches how you want failures handled.
| Combinator | Resolves when | Rejects when | Typical use |
|---|---|---|---|
| `Promise.all` | every promise fulfills | the first rejection | all results are required |
| `Promise.allSettled` | every promise settles | never | collect successes and failures separately |
| `Promise.any` | the first fulfillment | all reject (`AggregateError`) | try several mirrors, keep the first that works |
| `Promise.race` | the first settlement | the first settlement is a rejection | timeouts |
Promise.all fails fast, but it does not cancel anything. When one task rejects, the others keep running and their results are discarded. If those tasks write data or hold connections, you have to cancel them yourself, for example with an AbortController passed to fetch.
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
const results = await Promise.allSettled([
sleep(100, 'ok'),
Promise.reject(new Error('bad input')),
sleep(50, 'also ok')
]);
for (const r of results) {
if (r.status === 'fulfilled') console.log('value:', r.value);
else console.log('error:', r.reason.message);
}
}
main();
// value: ok
// error: bad input
// value: also okBounded Concurrency: The Middle Ground
Running every task at once is not always better. With 10,000 URLs, Promise.all(urls.map(fetch)) opens thousands of requests together. That can hit rate limits, run out of sockets, or use too much memory. Fully sequential processing is safe but slow. The usual fix is a fixed number of workers that each take the next item when they finish.
async function mapLimit(items, limit, worker) {
const results = new Array(items.length);
let nextIndex = 0;
async function runner() {
while (nextIndex < items.length) {
const i = nextIndex++; // claim an index synchronously
results[i] = await worker(items[i], i);
}
}
const runners = Array.from(
{ length: Math.min(limit, items.length) },
() => runner()
);
await Promise.all(runners);
return results;
}
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function main() {
const start = Date.now();
const out = await mapLimit([100, 100, 100, 100, 100, 100], 2, (ms, i) =>
sleep(ms, `task ${i}`)
);
console.log(out, `${Date.now() - start} ms`); // six tasks, two at a time, ~300 ms
}
main();This works safely in single-threaded JavaScript because nextIndex++ runs synchronously. No other runner can execute between reading the index and incrementing it. Results go into their original positions, so the output order matches the input order.
If one worker throws, Promise.all(runners) rejects. The other runners keep pulling items until the list runs out. To stop them early, add a shared failed flag that each runner checks at the top of its loop.
Batching an Async Iterable
mapLimit needs an array. If your items come from an async iterable, such as a paginated API or a file, you can't map over everything up front. You can still group items into batches and run each batch concurrently:
async function* inBatches(source, size) {
let batch = [];
for await (const item of source) {
batch.push(item);
if (batch.length === size) {
yield batch;
batch = [];
}
}
if (batch.length > 0) yield batch;
}
const sleep = (ms, value) =>
new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function* ids() {
for (let i = 1; i <= 7; i++) {
await sleep(10);
yield i;
}
}
async function main() {
for await (const batch of inBatches(ids(), 3)) {
const users = await Promise.all(batch.map((id) => sleep(100, `user${id}`)));
console.log(users);
}
}
main();
// [ 'user1', 'user2', 'user3' ]
// [ 'user4', 'user5', 'user6' ]
// [ 'user7' ]The outer for await...of keeps backpressure: the generator doesn't read a new batch until the current one finishes. Inside each batch the work runs concurrently. Batching is simpler than a worker pool. Its weakness is that each batch is as slow as its slowest item, because the fast workers wait for the slow one. A worker pool keeps every slot busy.
Calling next() Concurrently Does Not Parallelize a Generator
You might try to speed up an async generator by calling next() several times without awaiting:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function* slow() {
for (let i = 1; i <= 3; i++) {
await sleep(100);
yield i;
}
}
async function main() {
const it = slow();
const start = Date.now();
const results = await Promise.all([it.next(), it.next(), it.next()]);
console.log(results.map((r) => r.value), `${Date.now() - start} ms`);
}
main(); // [ 1, 2, 3 ] ~300 msAsync generators queue the requests. The generator body still runs one step at a time, so the three next() calls take 300 ms in total. If you want concurrency, the generator itself has to start several operations at once, for example by yielding the results of Promise.all on each page.
Common Mistakes
forEachwith an async callback.items.forEach(async (x) => await save(x))starts every task right away and returns without waiting for any of them. Errors become unhandled rejections. Usefor...ofwithawaitfor sequential work, orPromise.all(items.map(...))for concurrent work.- Forgetting
Promise.allaroundmap.const users = items.map(async (id) => getUser(id))gives you an array of promises, not users. - Sequential awaits that don't depend on each other.
const a = await getA(); const b = await getB();waits twice when it only needs to wait once. Writeconst [a, b] = await Promise.all([getA(), getB()]);. - Unbounded fan-out over large inputs. Use a worker pool or batches when the input size is not small and fixed.
Decision Criteria
| Situation | Pattern |
|---|---|
| Each step needs the previous result (pagination cursors, ordered writes) | `for await...of` or `await` in a loop |
| A source produces values over time and you must respect backpressure | `for await...of` |
| A few independent tasks, all required | `Promise.all` |
| Independent tasks where partial failure is acceptable | `Promise.allSettled` |
| Many independent tasks, limited by an API or resources | worker pool such as `mapLimit` |
| Items come from an async iterable but each item's work is independent | batches inside `for await...of` |
Exercise
A function runs for (const id of [1, 2, 3, 4]) { results.push(await fetchUser(id)); } and each fetchUser call takes about 250 ms. Roughly how long does it take, and how would you rewrite it to finish in about 250 ms while keeping the results in id order?
Show answer
It takes about 1000 ms because each call starts only after the previous one finishes. Write const results = await Promise.all([1, 2, 3, 4].map((id) => fetchUser(id)));. All four requests start together, the total is about 250 ms, and Promise.all returns the results in input order.
Exercise
Why can for await (const v of [slowPromise, rejectingPromise]) crash a Node.js process when Promise.all([slowPromise, rejectingPromise]) would not?
Show answer
for await...of attaches a handler only to the promise it is currently waiting on. While it waits on slowPromise, rejectingPromise rejects with no handler attached, so Node.js reports an unhandled rejection. The default since Node.js 15 is to exit. Promise.all attaches handlers to every promise immediately, so the rejection is handled and surfaces as a single rejection of the combined promise.
Exercise
Using the mapLimit function from this chapter with a limit of 3, how long does it take to process five tasks that each take 200 ms, and why?
Show answer
About 400 ms. Three runners start tasks 0, 1, and 2 at time 0. At 200 ms, two runners take tasks 3 and 4 while the third finds no work left and stops. Those two tasks finish at 400 ms.