Sub topic 8
Sequential or Parallel: Awaiting Multiple Operations
This chapter assumes you are comfortable with await, with try/catch in async functions, and with Promise.all and Promise.allSettled from the previous chapters. You should also be able to run scripts in Node.js 16 or later. In Node.js 16+, performance.now() is available globally, which the timing examples rely on.
When a function needs the results of several asynchronous operations, you choose how to wait for them. You can wait for each one to finish before starting the next, which is sequential execution. You can also start them all and wait for the whole group, which is parallel execution. Both give the same values. They can differ a lot in total time, in how failures behave, and in how much load you put on other systems.
The Core Rule: When a Promise Starts
The most important idea in this chapter is that work starts when you call the function that returns the Promise, not when you await it. await only decides where your function pauses to collect a result.
The two lines below look nearly the same, but they behave differently:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function demo() {
// Version 1: call, then immediately await. The next call waits for this one.
const a1 = await delay(500, 'a');
// Version 2: call now, await later. The timer is already running.
const pending = delay(500, 'b');
// ...other code can run here while the timer counts down...
const b1 = await pending;
return [a1, b1];
}
demo().then(console.log); // [ 'a', 'b' ] after about 1 secondIn version 1, delay cannot be called again until the first await resumes. In version 2, the timer starts at the delay(...) call, and await pending just collects the value later. Every sequential-versus-parallel decision comes down to where you put the calls relative to the awaits.
Measuring the Difference
Do not guess at timing. Measure it. The helper below times any async function:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function timed(label, fn) {
const start = performance.now();
const result = await fn();
const elapsed = Math.round(performance.now() - start);
console.log(`${label}: ${elapsed} ms ->`, result);
return result;
}
async function sequential() {
const a = await delay(300, 'a');
const b = await delay(200, 'b');
const c = await delay(100, 'c');
return [a, b, c];
}
async function parallel() {
const [a, b, c] = await Promise.all([
delay(300, 'a'),
delay(200, 'b'),
delay(100, 'c')
]);
return [a, b, c];
}
async function main() {
await timed('sequential', sequential); // about 600 ms
await timed('parallel', parallel); // about 300 ms
}
main();The sequential version takes the sum of the durations (300 + 200 + 100). The parallel version takes the maximum (300). Both return ['a', 'b', 'c'] in the same order. Promise.all returns results in the order of its input array, not the order the operations finish.
In the chart, each day on the axis stands for 100 ms.
"Parallel" here means concurrent waiting. JavaScript still runs your code on one thread. The overlap comes from timers, network requests, and file I/O, which the host environment handles while your code is paused. If each operation is CPU-heavy synchronous work, such as a long loop, Promise.all will not make it faster. Each piece still blocks the thread in turn.
When Sequential Is Correct
Sequential execution is not a mistake when one step needs the result of the step before it:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const getUser = id => delay(100, { id, teamId: 7 });
const getTeam = teamId => delay(100, { teamId, name: 'Platform' });
async function loadTeamForUser(id) {
const user = await getUser(id); // must finish first
const team = await getTeam(user.teamId); // needs user.teamId
return { user, team };
}
loadTeamForUser(1).then(console.log);Sequential execution is also right when the order of side effects matters. Examples are database migrations, writes that must happen before later reads, and steps that must stop at the first failure without starting the rest. It is also right when you must deliberately limit load, for example on an API that rejects bursts of requests.
The mistake is accidental sequencing. That happens when operations are independent but each one is awaited on its own line out of habit.
Mixed Dependencies
Real code often has some steps that depend on earlier ones and some that do not. Run each independent group in parallel and keep the dependent steps after the results they need:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const getUser = id => delay(200, { id, name: 'Ada' });
const getPosts = userId => delay(300, [`post by ${userId}`]);
const getSettings = userId => delay(250, { theme: 'dark', userId });
const getAnnouncements = () => delay(400, ['maintenance on Friday']);
async function loadDashboard(id) {
// Announcements do not depend on the user, so start them immediately.
const announcementsPromise = getAnnouncements();
const user = await getUser(id); // 200 ms
// Posts and settings both need the user, but not each other.
const [posts, settings] = await Promise.all([
getPosts(user.id),
getSettings(user.id)
]); // +300 ms
const announcements = await announcementsPromise; // already done at 400 ms
return { user, posts, settings, announcements };
}
const start = performance.now();
loadDashboard(1).then(result => {
console.log(result);
console.log(`took ${Math.round(performance.now() - start)} ms`); // about 500
});A fully sequential version would take 200 + 300 + 250 + 400 = 1150 ms. This version takes about 500 ms, which is the longest dependency path: user (200) then posts (300). When you optimize, find the longest chain of operations that truly depend on each other. That chain is the lowest total time you can reach.
The Unhandled Rejection Gotcha
The "start now, await later" pattern has a trap. If you start several Promises and await them one at a time, a later Promise can reject while you are still waiting on an earlier one. At that moment, nothing is listening for its rejection.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const failAfter = (ms, msg) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), ms));
async function risky() {
const slow = delay(1000, 'slow');
const fast = failAfter(100, 'fast failed');
try {
const a = await slow; // still waiting when `fast` rejects at 100 ms
const b = await fast;
return [a, b];
} catch (err) {
console.log('caught:', err.message);
}
}
risky();At 100 ms, fast rejects with no handler attached. Node.js 15 and later treat this as an unhandled rejection and, by default, terminate the process before await fast is reached. The try/catch never gets the chance to run. Browsers log an "Uncaught (in promise)" error instead.
The fix is to hand the whole group to a combinator, which attaches handlers to every Promise right away:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const failAfter = (ms, msg) =>
new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), ms));
async function safe() {
try {
const [a, b] = await Promise.all([
delay(1000, 'slow'),
failAfter(100, 'fast failed')
]);
return [a, b];
} catch (err) {
console.log('caught:', err.message); // caught: fast failed (at about 100 ms)
}
}
safe();Failure Behavior: Fail-Fast Does Not Cancel
Promise.all rejects as soon as any input rejects, which is fail-fast behavior. That does not stop the other operations. Their timers keep running, their requests stay in flight, and their side effects still happen. Only their results are thrown away.
| Approach | Total time (all succeed) | First failure | Other operations after a failure |
|---|---|---|---|
| Sequential `await` | Sum of durations | Stops; later steps never start | Not started |
| `Promise.all` | Longest duration | Rejects immediately | Keep running, results discarded |
| `Promise.allSettled` | Longest duration | Never rejects | Run to completion, all outcomes reported |
If later operations must not start after a failure, use sequential execution. If you need every outcome, use Promise.allSettled. If in-flight work must actually stop, you need cancellation, which a later chapter covers with AbortController.
Loops: Sequential and Parallel Forms
Running an async operation for every item in an array has the same two forms:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const fetchItem = id => delay(200, `item-${id}`);
async function oneByOne(ids) {
const results = [];
for (const id of ids) {
results.push(await fetchItem(id)); // waits each turn
}
return results;
}
async function allAtOnce(ids) {
return Promise.all(ids.map(id => fetchItem(id))); // all start in map
}
async function main() {
const ids = [1, 2, 3, 4, 5];
let t = performance.now();
console.log(await oneByOne(ids), Math.round(performance.now() - t), 'ms'); // ~1000
t = performance.now();
console.log(await allAtOnce(ids), Math.round(performance.now() - t), 'ms'); // ~200
}
main();ids.map(...) calls fetchItem for every id right away, so all five operations are in flight before Promise.all waits on them.
Limiting Concurrency
Full parallelism over a large array can cause harm. Starting 10,000 requests at once can exhaust sockets or memory, trigger rate limits, or overload a database. The middle ground is a fixed number of concurrent workers:
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function mapWithLimit(items, limit, fn) {
const results = new Array(items.length);
let next = 0;
async function worker() {
while (next < items.length) {
const index = next++; // claimed synchronously, so no two workers share an index
results[index] = await fn(items[index], index);
}
}
const workerCount = Math.min(limit, items.length);
await Promise.all(Array.from({ length: workerCount }, () => worker()));
return results;
}
async function main() {
const ids = Array.from({ length: 10 }, (_, i) => i + 1);
const start = performance.now();
const results = await mapWithLimit(ids, 3, id => delay(200, `item-${id}`));
console.log(results);
console.log(`${Math.round(performance.now() - start)} ms`); // about 800 (4 rounds of 200)
}
main();next++ is safe without locks because only one piece of JavaScript runs at a time. Each worker claims an index synchronously, before its own await. Results go into their original positions, so the output order matches the input order. Like Promise.all, this helper rejects on the first failure while the other workers keep going. Wrap fn in a try/catch if you want to collect errors instead.
Choosing an Approach
- Steps depend on each other, or must stop at the first failure: sequential
await. - Independent and few in number, all must succeed:
Promise.all. - Independent, and partial success is useful:
Promise.allSettled. - Independent but many, or a shared resource is limited: a concurrency limit.
- A mix of these: draw the dependencies, run each independent group in parallel, and measure.
Exercise
A function runs const a = await getA(); const b = await getB(); const c = await getC(a); where getA takes 400 ms, getB takes 300 ms, and getC takes 100 ms. getB does not depend on anything. Rewrite it to be as fast as possible and state the new total time.
Show answer
Start getB before awaiting getA: const bPromise = getB(); const a = await getA(); const [b, c] = await Promise.all([bPromise, getC(a)]);. Using Promise.all for the second await makes sure a rejection from bPromise is always handled. The longest dependency chain is getA then getC, so the total drops from 800 ms to about 500 ms.
Exercise
Why can const p1 = slowTask(); const p2 = quickFailingTask(); await p1; await p2; crash a Node.js process even inside try/catch, and what is the fix?
Show answer
p2 rejects while the function is still paused on await p1, and at that point no handler is attached to p2. Node.js reports an unhandled rejection and, by default, exits. Await both together with await Promise.all([p1, p2]) (or Promise.allSettled), which attaches handlers to both Promises immediately.
Exercise
You must call an API for 500 ids, and the API allows at most 5 concurrent requests. Each request takes about 100 ms. Roughly how long do the for...of, Promise.all, and mapWithLimit(ids, 5, ...) approaches take, and which one should you use?
Show answer
for...of takes about 500 × 100 ms = 50 seconds. Promise.all starts all 500 at once, about 100 ms in theory, but it breaks the API's limit and will likely be throttled or rejected. mapWithLimit with a limit of 5 takes about 500 / 5 × 100 ms = 10 seconds and respects the limit, so use mapWithLimit.