Concept Explanation
async/await is perfect for one task at a time. But what if you need three API calls at once? Awaiting them one by one is slow — each waits for the last to finish. Promise combinators run many promises together and combine their results.
The four you'll actually use:
Promise.all— wait for all to succeed; reject the instant one fails.Promise.allSettled— wait for all to finish, success or failure, and report each.Promise.race— settle as soon as the first one settles (win or lose).Promise.any— resolve with the first success, ignoring the failures.
Syntax or Core Structure
Run in parallel with Promise.all
// Sequential: ~3 seconds total (slow)
const user = await getUser();
const posts = await getPosts();
const stats = await getStats();
// Parallel: ~1 second total (fast)
const [user, posts, stats] = await Promise.all([
getUser(), getPosts(), getStats()
]);
Survive partial failure with allSettled
const results = await Promise.allSettled([apiA(), apiB(), apiC()]);
results.forEach(r => {
if (r.status === "fulfilled") console.log(r.value);
else console.warn("Failed:", r.reason);
});
Real World Example
A dashboard that loads your profile, notifications, and recent orders should fire all three requests at once with Promise.all, not one after another. Promise.race powers timeouts too: race your fetch against a "reject after 5s" promise, and whichever finishes first wins.
Common Mistakes
Promise.allis all-or-nothing: one rejected promise throws away every result. UseallSettledwhen partial success is acceptable.- Awaiting inside a loop:
for (const id of ids) await fetch(id)runs them one at a time. Map to promises andPromise.allthe array instead. - Passing references, not calls: combinators need an array of promises, so call the functions —
getUser(), notgetUser.
Best Practices
- Parallel by default: if tasks don't depend on each other, run them together.
- Pick the right combinator: need every result ->
all; need a report of each ->allSettled; need the fastest ->race/any. - Always handle rejection: wrap
Promise.allintry/catch, or an unhandled rejection can crash Node.
Practice Exercises
- The Parallel Loader: Fetch three JSONPlaceholder resources with
Promise.alland log all three once they're ready. - The Resilient Batch: Use
Promise.allSettledon a mix of good and bad URLs and print which ones succeeded. - The Timeout: Use
Promise.raceto reject a fetch if it takes longer than 2 seconds.