How can awaiting inside a loop make code slow, and how do you run async tasks in parallel?
Each await pauses until that task finishes, so awaiting one after another runs them in sequence. Start all the promises first and await them together with Promise.all to run them in parallel.
Explain it simply
Think of boiling two pots on a stove. Sequential: start pot one, stare at it until it boils, then start pot two. Total time is both added. Parallel: light both burners, then wait for both. Total time is the longest one.
await in a row does the first thing: the second call does not even start until the first has finished. If the calls do not depend on each other, that wastes time.
Create all the promises first (calling the async functions starts them), then wait with Promise.all. If you need sequential order on purpose, for example rate limits or dependent steps, use for...of with await.
Example
const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
async function sequential() {
const a = await wait(100, "a"); // starts, waits 100ms
const b = await wait(100, "b"); // only now starts, waits 100ms
return a + b; // about 200ms
}
async function parallel() {
const [a, b] = await Promise.all([wait(100, "a"), wait(100, "b")]);
return a + b; // about 100ms
}
sequential().then(console.log); // -> ab
parallel().then(console.log); // -> abBoth give ab; the second finishes in about half the time.
What to say in the interview
"Back-to-back awaits run sequentially, since each starts after the previous finishes. For independent work I start all promises first and await Promise.all, so total time is the slowest task instead of the sum. I keep sequential awaiting only for dependent steps or rate limits."
Common mistakes
- Using await inside map and expecting it to be sequential. It starts all of them at once.