The Promise object in JavaScript offers a few useful built-in methods, with Promise.all
and Promise.race
being two such methods. Even though these two methods both take arrays of promises as argument, there’s a big difference between Promise.all
vs Promise.race
.
Promise.all
accepts an array of promises, and will attempt to fulfill all of them. BUT it will exit early if just 1 promise gets rejected.
Promise.race
also accepts an array of promises, but returns the first promise that is settled. A settled promise can either be resolved or rejected. Think of a race, the first one to come first, wins
Promise.all()
The design purpose of Promise.all is to fulfill many promises. For example, when a user logs into a web app like Facebook, several network requests probably need to be made to populate the user’s personalized content:
const userContent = [
new Promise(getFriendsList),
new Promise(getGroups),
new Promise(getLikedPages)
];
function initalizeUserContent() {
Promise.all(userContent) // 👈 gotta get em all!
.then(displayHomepage) // if all good, the homepage is displayed
.catch(redirectLoginForm); // if something went wrong, redirect to login page
};
initalizeUserContent();
Promise.race()
This one is somewhat different. You still give it an array of promises, but it exits with the first settled promise.
Imagine if you’re developing software to purchase stocks on the NASDAQ exchange. You want to be able to submit purchases (called “buy orders”) to several stockbrokers, but you’re only going to honor the first stockbroker that fulfills your order.
const myStockBrokers = [
eTrade,
fidelity,
interactiveBrokers,
ameritrade,
tradeStation,
vanguard
];
function submitBuyOrder() {
Promise.race(myStockBrokers)
.then(updateMyPortfolio)
.catch(cancelBuyOrder);
};
submitBuyOrder();
The method name Promise.race is befitting because it causes all of the promises to “race” against each other with only a single winner.
Rule of thumb
A helpful tip is to think about the returned value that you want. Do you want an array of promise results? Or, do you simply want the results of the first settled promise?