Promise.all and Promise.race
Promise.all() waits for all promises to finish.
Promise.race() resolves or rejects as soon as the first promise finishes.
Promise.all
Use Promise.all() when multiple async tasks must all finish before continuing.
const [user, posts] = await Promise.all([
fetch("/api/user").then(res => res.json()),
fetch("/api/posts").then(res => res.json())
]);Promise.race
Use Promise.race() when the first finished promise matters.
const result = await Promise.race([
fetch("/api/data"),
new Promise((_, reject) =>
setTimeout(() => reject(new Error("Timeout")), 3000)
)
]);Difference
| Method | Finishes when |
|---|---|
Promise.all() | every promise succeeds, or one rejects |
Promise.race() | the first promise settles |