The Performance Cost of Sequential Awaits
You'll learn why sequential await statements can dramatically slow down your code when operations could run in parallel.
The Hidden Time Penalty
When you write multiple await statements one after another, JavaScript waits for each operation to completely finish before starting the next one. If these operations don't depend on each other, you're wasting valuable time.
Think of it like running errands: if you need to mail a letter and buy groceries, doing them sequentially means you finish the post office, drive home, then drive to the grocery store. Running them concurrently is like dropping off the letter on your way to the store—both tasks complete in roughly the time of the longest one.
Measuring the Cost
async function sequential() {
const start = Date.now();
const result1 = await delay(1000); // waits 1 second
const result2 = await delay(1000); // waits ANOTHER 1 second
const elapsed = Date.now() - start;
console.log(`Sequential: ${elapsed}ms`); // ~2000ms
}
async function concurrent() {
const start = Date.now();
const promise1 = delay(1000); // starts immediately
const promise2 = delay(1000); // also starts immediately
const result1 = await promise1; // both running in parallel
const result2 = await promise2;
const elapsed = Date.now() - start;
console.log(`Concurrent: ${elapsed}ms`); // ~1000ms
}
The sequential version takes twice as long because each await blocks the next operation from starting. The concurrent version starts both operations immediately, then awaits their results.
Key Takeaway: Sequential awaits add their wait times together; when operations are independent, start them all first, then await the results to cut your total time dramatically.