Sub topic 2
Awaiting One by One Versus Starting Everything at Once
This chapter assumes you can write async functions, use await, and create a promise with new Promise. It also assumes you know that timers and network calls run in the background while JavaScript continues with other code.
When code has several independent async tasks, you can either wait for each one before starting the next or start them all and then wait. The two versions look almost the same in code, but the total time can differ a lot.
The Key Fact: Work Starts When the Promise Is Created
A promise does not wait for await before it starts. Calling fetch(url) or setTimeout starts the work right away. await only pauses the current function until a promise that already exists settles.
So the total time depends on when you create each promise, not on where you put await.
Sequential: Each Wait Adds Up
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function sequential() {
const a = await delay(100, 'a'); // timer 1 starts, function pauses
const b = await delay(200, 'b'); // timer 2 starts only after timer 1 finishes
return [a, b];
}
async function main() {
console.time('sequential');
console.log(await sequential()); // ['a', 'b']
console.timeEnd('sequential'); // about 300 ms
}
main();The second delay call does not run until the first await resumes. The waits happen one after another: 100 + 200 = 300 ms.
Concurrent: Start First, Then Wait
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function concurrent() {
return Promise.all([delay(100, 'a'), delay(200, 'b')]);
}
async function main() {
console.time('concurrent');
console.log(await concurrent()); // ['a', 'b']
console.timeEnd('concurrent'); // about 200 ms
}
main();Both delay calls run while the array is being built, so both timers are running together. The total time is set by the slowest task: about 200 ms. Later chapters explain in detail how Promise.all combines the results.
Common Errors
Awaiting Inside a Loop by Accident
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
async function loadAll(ids) {
const results = [];
for (const id of ids) {
results.push(await delay(100, id)); // one at a time
}
return results;
}
loadAll([1, 2, 3, 4, 5]).then(console.log); // [1, 2, 3, 4, 5] after about 500 msIf the tasks don't depend on each other, map them to promises first: Promise.all(ids.map((id) => delay(100, id))) finishes in about 100 ms.
Starting Early but Awaiting Separately
const pa = delay(100, 'a');
const pb = delay(200, 'b');
const a = await pa;
const b = await pb;This version is also concurrent, because both promises exist before the first await. It has a hidden risk, though. If pb rejects while the function is still waiting on pa, no handler is attached to pb yet. The runtime can report an unhandled rejection, and Node.js exits the process by default when that happens. Passing the promises to a combinator attaches handlers to all of them immediately.
Running Dependent Tasks Concurrently
Sequential code is correct when one step needs the result of another, such as getting a user ID and then fetching that user's orders. Run tasks concurrently only when they are independent.
| Pattern | Total time | Use when |
|---|---|---|
| `await` one by one | Sum of all tasks | Each step needs the previous result |
| Start all, then combine | Slowest task | Tasks are independent |
Exercise
A function runs const x = await delay(300, 1); const y = await delay(300, 2);. How long does it take, and how would you rewrite it so it takes about 300 ms?
Show answer
About 600 ms, because the second timer only starts after the first await resumes. Rewrite it as const [x, y] = await Promise.all([delay(300, 1), delay(300, 2)]); so both timers start at once.
Exercise
Why is const p1 = task1(); const p2 = task2(); await p1; await p2; concurrent, and what risk does it carry?
Show answer
Both tasks start when their promises are created, before any await runs. If p2 rejects while the function is still awaiting p1, p2 has no handler yet, so the runtime can report an unhandled rejection.