Advanced Async Patterns
Prerequisites: Async/await
Promise.all runs several async operations concurrently and waits
for all of them; Promise.race resolves as soon as the first one
settles.
const [user, posts] = await Promise.all([
fetch("/api/user").then((r) => r.json()),
fetch("/api/posts").then((r) => r.json()),
]);
This runs both requests at the same time rather than one after another — if each takes 1 second, the total wait is about 1 second, not 2.
Common mistakes
- Writing two sequential
awaitcalls when the operations don't depend on each other — this needlessly doubles the wait time compared toPromise.all.