Async Patterns & Promise.all
Recap async/await, then run several async tasks at once with Promise.all — the difference between a snappy page and a slow one.
Don't wait in line when you can wait together
You met async/await in the Data Fetching module: mark a function async, then await a Promise to get its result. That's the foundation. Here's the upgrade that matters for real apps.
When a page needs several pieces of data, awaiting them one after another is wasteful — each waits for the previous to finish:
const user = await fetchUser(); // wait 300ms...
const posts = await fetchPosts(); // ...THEN wait another 300ms = 600ms totalIf the requests don't depend on each other, start them all at once with Promise.all. It takes an array of Promises and resolves when they've all finished — in parallel:
const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);
// both run together — about 300ms totalNotice the array destructuring on the left — Promise.all returns results in the same order you passed them in.
Promise.all sends everyone out at once and waits for the last one back. Same errands, a fraction of the time.Promise.all rejects as soon as any one Promise fails — so wrap it in try/catch. If you'd rather get every result regardless of individual failures, use Promise.allSettled, which always resolves with the status of each.