Sub topic 8
Sequential or Parallel: Awaiting Multiple Operations
This chapter assumes you can write async functions, use await, and handle errors with try/catch. It also assumes you have seen Promise.all in the chapter on combinators. Here you will learn how the placement of await controls whether independent operations overlap in time or run one after another.
The Core Rule: A Promise Starts Work When It Is Created
Calling a function that returns a Promise starts the operation right away. await does not start anything. It only pauses the current async function until a Promise that already exists settles. As a result, where you create Promises and where you await them decides the total running time.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function sequential() {
const a = await delay(1000, 'a'); // starts, then waits 1 s
const b = await delay(1000, 'b'); // starts only after a finishes
return [a, b]; // about 2 seconds
}
async function parallel() {
const [a, b] = await Promise.all([
delay(1000, 'a'), // both timers start immediately
delay(1000, 'b')
]);
return [a, b]; // about 1 second
}In sequential, the second delay call does not happen until the first await resumes. In parallel, both calls run while the array is being built, so the timers overlap.
Measuring the Difference
Don't guess about timing. Measure it. performance.now() is available in browsers and in Node.js 16 and later.
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 ms = Math.round(performance.now() - start);
console.log(`${label}: ${ms} ms`, result);
}
async function main() {
await timed('sequential', async () => {
const a = await delay(500, 'a');
const b = await delay(500, 'b');
return [a, b];
});
await timed('parallel', () =>
Promise.all([delay(500, 'a'), delay(500, 'b')])
);
}
main();
// sequential: ~1000 ms [ 'a', 'b' ]
// parallel: ~500 ms [ 'a', 'b' ]When Sequential Is Correct
Run operations in sequence when a later step needs the result of an earlier one, or when the order of side effects matters, such as writing records that must arrive in order. Run them in parallel when they are independent.
Real code often mixes both patterns. In the example below, the posts and the settings both depend on the user, but they don't depend on each other.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
const getUser = id => delay(300, { id, name: 'Ada' });
const getPosts = userId => delay(300, [`post by ${userId}`]);
const getSettings = userId => delay(300, { theme: 'dark', userId });
async function loadProfile(id) {
const user = await getUser(id); // must come first
const [posts, settings] = await Promise.all([
getPosts(user.id), // independent of each other
getSettings(user.id)
]);
return { user, posts, settings }; // about 600 ms, not 900 ms
}
loadProfile(7).then(console.log);Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Page loads slowly even though requests are unrelated | Each `await` sits on its own line, so the requests form a chain | Start the requests together and await `Promise.all` |
| Wrong or missing data | Dependent steps were run in parallel | Await the step that supplies the input first |
| "Unhandled promise rejection" warning | Promises were started early and then awaited one at a time | Await them through `Promise.all` instead |
| Server rate limit errors | Hundreds of requests were started at once | Process the work in batches of limited size |
The third row needs a closer look. You can start Promises early and await them separately:
const p1 = delay(1000, 'a');
const p2 = Promise.reject(new Error('fast failure'));
const a = await p1;
const b = await p2;This code is parallel, but nothing handles p2's rejection while the function is waiting on p1. The runtime can report that rejection as unhandled, and in Node.js an unhandled rejection crashes the process by default. Promise.all attaches handlers to every Promise right away and rejects as soon as any one of them fails.
Exercises
Exercise
A function awaits three independent requests on separate lines. They take 200 ms, 500 ms, and 300 ms. About how long does it take, and how long would it take with Promise.all?
Show answer
Sequentially it takes about 1000 ms, the sum of the three. With Promise.all it takes about 500 ms, the time of the slowest request.
Exercise
Rewrite this code so the two requests overlap: const a = await fetchA(); const b = await fetchB(); (fetchB does not use a).
Show answer
const [a, b] = await Promise.all([fetchA(), fetchB()]); Both calls start before any await, so their durations overlap.
Exercise
Why is const p = fetchA(); const q = fetchB(); const a = await p; const b = await q; riskier than Promise.all?
Show answer
If q rejects while the function is still waiting on p, nothing is handling q's rejection yet. The runtime can report it as unhandled, and Node.js may crash. Promise.all attaches handlers to both Promises immediately.