Sub topic 2
Awaiting One by One Versus Starting Everything at Once
This chapter assumes you can write async functions, use await inside try/catch, and create promises with new Promise. It also assumes you know that timers and network requests finish later, on the event loop, while your code keeps running. The previous chapter's recap of pending, fulfilled, and rejected states is all the promise theory you need here.
The main question is when the asynchronous work actually starts. Once you know that, the speed difference between the two styles of code below makes sense, and so do the bugs that appear when people try to fix it by hand.
Promises Start Work When Created, Not When Awaited
A promise is not a recipe waiting to be run. When you call a function that returns a promise, the underlying operation (a timer, a file read, an HTTP request) usually begins right away. await does not start anything. It pauses the surrounding async function until a promise that already exists settles.
The following script logs when each task starts and finishes:
function task(name, ms) {
console.log(`start ${name}`);
return new Promise((resolve) => {
setTimeout(() => {
console.log(`done ${name}`);
resolve(name);
}, ms);
});
}
async function main() {
const p1 = task('A', 200);
const p2 = task('B', 100);
console.log('both started');
console.log(await p1, await p2);
}
main();
// start A
// start B
// both started
// done B
// done A
// A BBoth timers run while main is waiting on p1. By the time p1 fulfills at about 200 ms, p2 fulfilled long ago, so await p2 returns immediately. The total time is about 200 ms, the duration of the slowest task, and not 300 ms.
Sequential Await: Waiting Times Add Up
Code that writes await directly in front of every call creates each promise only after the previous one has settled:
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
// Sequential: about 300 ms in total
async function sequential() {
const a = await delay(100, 'a');
const b = await delay(200, 'b');
return [a, b];
}
// Concurrent: about 200 ms in total
async function concurrent() {
return Promise.all([delay(100, 'a'), delay(200, 'b')]);
}
async function time(label, fn) {
const start = performance.now();
const result = await fn();
console.log(label, result, `${Math.round(performance.now() - start)} ms`);
}
async function main() {
await time('sequential', sequential);
await time('concurrent', concurrent);
}
main();
// sequential [ 'a', 'b' ] ~300 ms
// concurrent [ 'a', 'b' ] ~200 msIn sequential, the second delay call does not run until the first await resumes. In concurrent, both calls are evaluated while the array literal is built, so both timers start together. Promise.all then waits for both. Later chapters cover how it works in detail.
With n independent tasks, sequential time is roughly the sum of their durations. Concurrent time is roughly the longest single duration. For ten API calls of 150 ms each, that is 1.5 seconds versus about 150 ms.
When Sequential Is Correct
Sequential awaiting is not a mistake in itself. It is the correct choice when one step needs the result of another, or when order matters for side effects.
async function loadDashboard(api, userId) {
// Must be sequential: orders need the account id from the user record.
const user = await api.getUser(userId);
// Independent of each other: start both, then wait.
const [orders, notifications] = await Promise.all([
api.getOrders(user.accountId),
api.getNotifications(user.id)
]);
return { user, orders, notifications };
}Most real code mixes the two styles. Draw the dependency graph, run each level of it concurrently, and await between levels.
| Situation | Style | Reason |
|---|---|---|
| Step B needs A's result | Sequential | B cannot be called until A's value exists |
| Writes must happen in order (migrations, appending to a log) | Sequential | Overlapping writes can corrupt order or state |
| Independent reads from different sources | Concurrent | Total time drops to the slowest read |
| Hundreds of requests to one server | Limited concurrency | Unbounded fan-out can trip rate limits or exhaust sockets |
| Retry until one source succeeds | Sequential or `Promise.any` | Depends on whether trying all sources at once is acceptable |
The last chapter covers limited concurrency for large batches.
Loops: Where Accidental Sequencing Hides
Loops are the most common place where code ends up sequential when nobody intended it, or concurrent when nobody intended that either.
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const ids = [1, 2, 3];
async function main() {
// 1. for...of with await: sequential, ~300 ms
const seq = [];
for (const id of ids) {
seq.push(await delay(100, id));
}
console.log('for...of', seq);
// 2. map then await all: concurrent, ~100 ms
const conc = await Promise.all(ids.map((id) => delay(100, id)));
console.log('map + Promise.all', conc);
// 3. forEach with an async callback: does NOT wait
const lost = [];
ids.forEach(async (id) => {
lost.push(await delay(100, id));
});
console.log('forEach', lost); // [] — the callbacks are still pending
}
main();forEach ignores the promise each callback returns, so main carries on before any of them finish. Any rejection inside those callbacks also has no handler. Use for...of when you want sequential work, and map plus a combinator when you want concurrent work.
The Hand-Rolled Concurrency Trap
Once you know that promises start eagerly, you might try to get concurrency without a combinator:
const delay = (ms, value) => new Promise((resolve) => setTimeout(() => resolve(value), ms));
const fail = (ms, msg) => new Promise((_, reject) => setTimeout(() => reject(new Error(msg)), ms));
async function main() {
const slow = delay(200, 'slow');
const broken = fail(50, 'broken');
try {
await slow; // paused here when `broken` rejects at 50 ms
await broken;
} catch (err) {
console.log('caught', err.message);
}
}
main();This works when everything succeeds. When broken rejects at 50 ms, though, nothing is attached to it yet, because main is still waiting on slow. The runtime sees a rejected promise with no handler.
The trap has a second cost. The code waits for slow before it can learn that broken failed, so the error reaches you late. Promise.all rejects as soon as any input rejects. The fail-fast chapter covers this behavior.
Concurrent Is Not Parallel
JavaScript runs your code on a single thread. "Concurrent" here means the waiting overlaps: several timers, sockets, or disk reads are in flight while the thread is free. CPU-heavy work does not speed up this way.
function busyWork(ms) {
const end = Date.now() + ms;
while (Date.now() < end) {} // blocks the thread
return Promise.resolve(ms);
}
async function main() {
const start = Date.now();
await Promise.all([busyWork(100), busyWork(100)]);
console.log(`${Date.now() - start} ms`); // ~200, not ~100
}
main();Each busyWork call blocks the thread before it returns a promise, so the two calls run one after the other. To run CPU work in parallel you need worker threads (worker_threads in Node, Web Workers in browsers). Promise combinators only help with I/O-bound waiting.
Summary of the Working Model
- Calling a promise-returning function starts the work.
awaitonly waits for it. awaitwritten directly in front of each call serializes the calls. The total time is the sum of the durations.- Start independent work first, then wait on all of it with a combinator. The total time is the slowest duration.
- Keep steps sequential when they depend on each other or must happen in order.
- Avoid awaiting separately created promises one at a time, because a later promise can reject with no handler attached.
- Overlapping waits saves time for I/O, not for CPU-bound code.
Exercise
A function runs const user = await getUser(); const posts = await getPosts(); const tags = await getTags();. Each call takes about 120 ms and none depends on another. Roughly how long does it take, and how would you rewrite it to take about 120 ms?
Show answer
About 360 ms, because each call starts only after the previous one settles. Rewrite it as const [user, posts, tags] = await Promise.all([getUser(), getPosts(), getTags()]); so all three requests are in flight at once and the total is set by the slowest, about 120 ms.
Exercise
Why does ids.forEach(async (id) => { await save(id); }); console.log('saved'); log "saved" before any save completes, and what are two correct replacements?
Show answer
forEach calls each async callback and discards the promise it returns, so nothing waits for those promises and their rejections go unhandled. Use for (const id of ids) { await save(id); } for sequential saves, or await Promise.all(ids.map((id) => save(id))); for concurrent saves.
Exercise
The code const a = fetchA(); const b = fetchB(); await a; await b; is wrapped in try/catch. fetchB rejects after 10 ms and fetchA fulfills after 500 ms. What happens in Node.js 18, and why?
Show answer
The process will most likely crash with an unhandled rejection. When fetchB's promise rejects at 10 ms, the function is still paused on await a, so nothing has attached a handler to b yet. Node treats that as unhandled and, by default, throws before the catch block can run. Using await Promise.all([fetchA(), fetchB()]) attaches handlers to both promises right away and rejects at about 10 ms.