Sub topic 14
Awaiting Inside Loops: Sequential vs Concurrent Work
This chapter assumes you know for...of loops, array methods such as map and forEach, and the basics of promises and async/await. In particular, you should know that an async function always returns a promise, and that await pauses only the function it appears in.
Loops and asynchronous code interact in ways that surprise many developers. The same list of tasks can take 40 milliseconds or 4 seconds depending on how you write the loop. A loop can also silently stop waiting for its work. This chapter covers the main patterns, how fast each one runs, and how each one handles errors.
The Core Distinction: When Work Starts
A promise does not start any work. The work starts when you call the function that creates the promise. await only decides when your code waits for a result. Keep this in mind for the rest of the chapter:
- Sequential work starts task 2 after task 1 finishes. Total time is roughly the sum of all task durations.
- Concurrent work starts every task before waiting on any of them. Total time is roughly the duration of the slowest task.
Every example below uses this helper. It returns a promise that resolves with ms after ms milliseconds:
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));Sequential: await Inside for...of
When await appears directly in a for...of body, each iteration pauses the whole function until its promise settles. The next iteration does not begin until then.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
async function sequential() {
const start = Date.now();
for (const ms of [30, 10, 20]) {
console.log(await delay(ms)); // 30, then 10, then 20
}
console.log("elapsed about", Date.now() - start, "ms"); // roughly 60
}
sequential();Use this pattern when order matters or when each step depends on the previous one. Typical cases are paging through an API where each response holds the next page's cursor, applying database migrations in order, and staying under a strict rate limit. Plain for, while, and do...while loops behave the same way. break, continue, return, and try...catch all work inside them as you would expect.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
async function firstSlowTask(durations, limit) {
for (const ms of durations) {
const result = await delay(ms);
if (result > limit) return result; // stops; later tasks never start
}
return null;
}
firstSlowTask([5, 15, 50], 10).then(console.log); // 15Concurrent: Promise.all with map
To run independent tasks at the same time, start them all first and then wait for all of them together. map calls the async function once per item. That call starts every task immediately and gives you an array of promises. Promise.all turns that array into one promise for an array of results.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
async function concurrent() {
const start = Date.now();
const results = await Promise.all([30, 10, 20].map(delay));
console.log(results); // [30, 10, 20]
console.log("elapsed about", Date.now() - start, "ms"); // roughly 30
}
concurrent();The results come back in the order of the input array, not the order in which the tasks finished. The 10 ms task finishes first, yet its result stays at index 1.
The forEach Trap
forEach ignores the return value of its callback. If you pass an async callback, each call returns a promise that nobody awaits. The tasks still run concurrently, but the surrounding function moves on without waiting for them.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
async function broken() {
[30, 10].forEach(async (ms) => {
console.log(await delay(ms));
});
console.log("done");
}
broken();
// done
// 10
// 30"done" prints first, and any rejection inside the callback escapes your try...catch. The same problem affects filter, some, and every with async callbacks. A promise is always truthy, so filter(async ...) keeps every element.
Errors: Fail Fast or Collect Everything
Promise.all rejects as soon as any input promise rejects, and it gives you that first error. The other tasks keep running, because promises cannot be cancelled, but you lose their results. When you want every outcome, use Promise.allSettled. It never rejects. It resolves with one { status, value } or { status, reason } object per task.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
const fail = (ms) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(`failed after ${ms}`)), ms));
async function main() {
try {
await Promise.all([delay(20), fail(10)]);
} catch (err) {
console.log("all:", err.message); // all: failed after 10
}
const outcomes = await Promise.allSettled([delay(20), fail(10)]);
for (const outcome of outcomes) {
if (outcome.status === "fulfilled") {
console.log("ok", outcome.value);
} else {
console.log("error", outcome.reason.message);
}
}
// ok 20
// error failed after 10
}
main();In a sequential for...of loop you can put try...catch inside the body. A failed item then gets logged and skipped while the loop moves on to the next one.
Limiting Concurrency
Starting 10,000 requests at once can exhaust sockets, trip rate limits, or overload a server. One middle ground is batching: run a fixed number of tasks concurrently, wait for the batch to finish, then start the next batch.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
async function inBatches(items, size, worker) {
const results = [];
for (let i = 0; i < items.length; i += size) {
const batch = items.slice(i, i + size);
const batchResults = await Promise.all(batch.map(worker));
results.push(...batchResults);
}
return results;
}
inBatches([30, 10, 20, 5, 15], 2, delay).then(console.log);
// [30, 10, 20, 5, 15] (about 30 + 20 + 15 = 65 ms)Batching is simple but wastes time. Each batch waits for its slowest task while the other slots sit idle. A worker pool fixes this: N async workers each pull the next item from a shared index until none remain. Libraries such as p-limit provide this ready-made.
for await...of and Async Iterables
for await...of loops over an async iterable, which is an object that produces values over time, such as an async generator, a Node.js readable stream, or a paginated API wrapper. Each iteration waits for the next value before running the body.
const delay = (ms) => new Promise((resolve) => setTimeout(() => resolve(ms), ms));
async function* countdown(n) {
while (n > 0) {
await delay(10);
yield n--;
}
}
async function main() {
for await (const value of countdown(3)) {
console.log(value); // 3, 2, 1
}
}
main();for await...of is always sequential with respect to the source. A break inside it calls the iterator's return method, which lets a generator or stream release its resources.
It also accepts a regular array of promises, awaiting each one in turn. This has a hazard. The promises already exist, so their work is already running. If a later promise rejects while the loop is still waiting on an earlier slow one, nothing is handling that rejection yet, and Node.js may report an unhandled rejection and exit. For an array of promises you already started, use Promise.all or Promise.allSettled.
Choosing a Pattern
| Pattern | Timing | Result order | On failure |
|---|---|---|---|
| `await` in `for...of` | Sum of durations | Input order | Stops at the first throw unless caught in the body |
| `Promise.all(items.map(fn))` | Slowest task | Input order | Rejects with the first error |
| `Promise.allSettled(items.map(fn))` | Slowest task | Input order | Never rejects; reports each outcome |
| Batches of N | Sum of each batch's slowest task | Input order | Depends on the inner combinator |
| `for await...of` | Paced by the source | Source order | Throws into the loop |
| `forEach(async ...)` | Not awaited | Completion order | Unhandled rejection |
Exercise
A function runs for (const id of ids) { results.push(await fetchUser(id)); } for 50 independent IDs, and each request takes about 100 ms. Roughly how long does it take, and how would you rewrite it to take about 100 ms while keeping results in ID order?
Show answer
It takes about 5 seconds (50 × 100 ms), because each request starts only after the previous one finishes. Rewrite it as const results = await Promise.all(ids.map(fetchUser));. This starts all 50 requests at once, and Promise.all returns the results in the same order as ids.
Exercise
Why does const active = users.filter(async (u) => await isActive(u)); return every user?
Show answer
An async callback always returns a promise, and every promise is truthy, so filter keeps every element. Resolve the checks first with const flags = await Promise.all(users.map(isActive));, then filter synchronously with users.filter((u, i) => flags[i]).
Exercise
You must call an API for 1,000 items, but the server allows at most 5 requests at a time, and one failed item should not abandon the rest. Which combination of patterns fits?
Show answer
Limit concurrency to 5 using batches of 5 or, better, a pool of 5 workers. Inside each batch, use Promise.allSettled, or have each worker catch its own errors, so that failures are recorded instead of rejecting the whole run.