Promise Combinators
Learn how to orchestrate multiple background tasks at the same time. Master Promise.all, Promise.race, and their modern counterparts.
The Big Four
When you have multiple independent asynchronous tasks, you shouldn't wait for them one by one. You should fire them all off at the same time.
JavaScript provides four static methods on the Promise object - known as combinators - to help you coordinate arrays of Promises.
The 'All or Nothing' Approach
Promise.all([p1, p2]) is the most common combinator. It waits for *every single promise* in the array to fulfill.
If they all succeed, it returns an array of all the results. However, it is an 'all or nothing' deal: if even ONE promise rejects, the entire Promise.all immediately rejects, ignoring the rest.
The Need for Speed
Promise.race([p1, p2]) acts like a literal foot race. It resolves or rejects the moment the *very first* promise settles.
It is commonly used to implement network timeouts (racing a fetch request against a setTimeout that rejects after 5 seconds).
All vs Race
Examine this visual breakdown of how the two most common combinators coordinate multiple background tasks.
Combinator Timelines
await Promise.all([
fetchUser(),
fetchPosts(),
fetchFriends()
]);
// Waits for the slowest to finish
await Promise.race([
fetchUser(),
timeoutTimer(5000)
]);
// Resolves/Rejects on the fastest
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Promise combinators allow you to coordinate arrays of asynchronous tasks.
Promise.allwaits for ALL to succeed, but fails immediately if ONE rejects.Promise.racetakes the VERY FIRST promise to settle, whether it succeeded or failed.Promise.allSettledwaits for ALL to finish, never rejecting.Promise.anytakes the FIRST success, only rejecting if they ALL fail.
Done with this concept?
Mark it complete to track your progress. No login needed.