Sequential by Accident
The commonest performance bug in async code is awaiting things one after another that had no reason to wait for each other.
Each await stops the function until that promise settles, so consecutive awaits run in series. When the operations are independent, start them all first and await afterwards, or use Promise.all. The fix is usually one line.
EXERCISE
1Three Awaits, Three Times the Wait
Reading top to bottom makes the cost invisible, because nothing in the code says it is slow.
The code that looks fine:
async function loadDashboard(userId) {
const user = await fetchUser(userId); // 300ms
const posts = await fetchPosts(userId); // 300ms
const settings = await fetchSettings(userId); // 300ms
return { user, posts, settings };
}
// total: about 900ms
Three requests, none of which needs anything from the others. All three take the same userId, which was available before the first line ran. Yet the second does not start until the first has finished.
That is not a quirk. It is exactly what await means: suspend until this settles. The function is doing precisely what it was told.
The fix, using the eagerness from Unit 5:
async function loadDashboard(userId) {
const userPromise = fetchUser(userId);
const postsPromise = fetchPosts(userId);
const settingsPromise = fetchSettings(userId);
return {
user: await userPromise,
posts: await postsPromise,
settings: await settingsPromise,
};
}
// total: about 300ms
All three requests are in flight before the first await runs. The awaits then collect results that are already arriving. Same three calls, same three awaits, three times faster.
Or more directly:
async function loadDashboard(userId) {
const [user, posts, settings] = await Promise.all([
fetchUser(userId),
fetchPosts(userId),
fetchSettings(userId),
]);
return { user, posts, settings };
}
Promise.all says the intent plainly: these three go together and none waits for another.
And the case where sequential is correct:
async function loadThread(id) {
const post = await fetchPost(id); // needed first
const author = await fetchUser(post.authorId); // needs post
const replies = await fetchReplies(post.id); // needs post
return { post, author, replies };
}
Line two needs post.authorId, so it genuinely has to wait. But lines two and three do not need each other, so the last two can still be combined:
const post = await fetchPost(id);
const [author, replies] = await Promise.all([
fetchUser(post.authorId),
fetchReplies(post.id),
]);
Read a run of awaits and ask, for each one, whether it uses a value produced by the line above. If it does not, those two lines are costing you time for nothing.
This is the highest-value thing to look for in an async code review, and it is fast to spot: consecutive await lines where no variable from the first appears in the second. It is invisible in testing against a local and very visible to a user on a slow connection, which is why it survives so long in real codebases.
EXERCISE
2Loops, and the forEach Trap
A loop over async work has three shapes with very different behaviour, and one of them does not wait at all.
forEach with an async callback does not wait:
async function saveAll(items) {
items.forEach(async (item) => {
await save(item);
});
console.log("all saved"); // prints immediately, nothing is saved yet
}
forEach discards whatever its callback returns, so the promises are created and abandoned. The log runs before any save completes, and a failure in any of them is an unhandled rejection.
This is worth remembering as a rule rather than a case: no array method waits for an async callback, with the single exception of nothing. map returns an array of promises, filter treats every promise as truthy, find returns the first item regardless.
const results = items.map(async (item) => save(item));
console.log(results); // [ Promise, Promise, Promise ]
That map behaviour is actually useful, which the next snippet uses.
for...of waits, one at a time:
async function saveAll(items) {
for (const item of items) {
await save(item); // strictly sequential
}
console.log("all saved");
}
This genuinely waits. Use it when order matters, when each step depends on the last, or when the operations must not overlap, such as writes to the same row.
Promise.all with map runs them together:
async function saveAll(items) {
await Promise.all(items.map((item) => save(item)));
console.log("all saved");
}
map builds the array of promises, Promise.all waits for all of them. This is the right default when the items are independent, and it is the one-line fix for the forEach version.
Choosing:
// Order matters, or steps depend on each other -> for...of with await
// Independent, and the list is small -> Promise.all(map)
// Independent, but the list is large -> a pool with a limit
// Never -> forEach with async
The pool from Unit 5 is the third case. Two thousand items handed to Promise.all starts two thousand operations at once.
And a subtle one: await inside a for loop with an index behaves the same:
for (let i = 0; i < items.length; i++) {
await save(items[i]); // sequential, same as for...of
}
The trap is specific to callback-taking array methods, not to loops in general.
Pro Tip: Treat
forEachwith anasynccallback as always wrong. There is no situation where it does what its author intended: if you wanted to wait, it does not, and if you did not want to wait,mapwithoutawaitsays so more honestly and gives you the promises to handle.
EXERCISE
3Finding It in Real Code
Accidental sequencing is invisible when you read the code and obvious the moment you measure it.
This bug survives because nothing looks wrong. Three sensible lines, each doing one thing. Here is how to find it deliberately.
Measure first, at the function level:
async function timed(label, fn) {
const start = performance.now();
try {
return await fn();
} finally {
console.log(`${label}: ${Math.round(performance.now() - start)}ms`);
}
}
const data = await timed("dashboard", () => loadDashboard(userId));
// dashboard: 912ms
finally means the timing is logged whether it succeeded or failed, which matters because a slow failure is still slow.
Then compare against the slowest single operation:
// If loadDashboard is 912ms and its slowest single fetch is 300ms,
// the extra 600ms is waiting that did not have to happen.
//
// A rough rule: total should be close to the slowest part,
// not to the sum of the parts.
That comparison is the whole diagnosis. If the total is near the sum of the parts, the calls are running in series; if it is near the largest part, they are running together. No profiler is needed for the judgement, only the two numbers.
In the browser, the network panel shows it directly:
// Requests that ran concurrently start at the same x position
// and their bars overlap.
//
// Requests that ran in series form a staircase, each starting
// where the previous one ended. The staircase IS the bug.
You do not need to read any code to spot a staircase, which makes this the fastest check available on a page you did not write. It is also the most convincing evidence to put in front of someone who does not believe the bug is real, because the picture needs no explanation.
And a review habit that catches it before it ships:
// For each run of consecutive awaits, ask one question:
// does line N use a variable produced by line N-1?
const user = await fetchUser(id);
const posts = await fetchPosts(id); // uses `id`, not `user` -> can be parallel
const post = await fetchPost(id);
const author = await fetchUser(post.authorId); // uses `post` -> must be serial
The question takes seconds per line and is reliable, because the dependency is always visible in the arguments.
One caution before parallelising everything:
// Ten concurrent requests to the same API may be rate-limited,
// and a hundred certainly will be. Concurrency is not free;
// it moves the cost from your user's time to the server's load.
The pool from Unit 5 is the answer when the list is large. For three dashboard fetches, Promise.all is simply correct.
