What is the difference between the promise combinators?
All three of them take a list of promises and give you back one promise, but they differ in two ways. They differ in when they settle, and they differ in what they do when one of the inputs fails.
Promise.all waits for every promise to succeed, and then it resolves with an array of all the results in the same order as the inputs. If any one of them fails, the returned promise rejects straight away with that reason. The other promises keep running in the background, but their results are thrown away.
Promise.race settles with whichever promise settles first, and that can be a success or a failure. This is the tool that you use to build a timeout, or to take the quickest answer from several sources.
Promise.allSettled waits for every promise to settle, and then it resolves with an array that describes the outcome of each one. Each entry says either that the promise was fulfilled and gives you its value, or that it was rejected and gives you its reason. It never rejects itself, and that is exactly why it is the right choice when you want to collect several results and treat each failure on its own instead of losing all of them.
function ok(value) {
return Promise.resolve(value);
}
function fail(message) {
return Promise.reject(new Error(message));
}
Promise.allSettled([ok(1), fail('bad'), ok(3)]).then(function (results) {
for (const result of results) {
if (result.status === 'fulfilled') {
console.log(result.status, result.value);
} else {
console.log(result.status, result.reason.message);
}
}
});
The ordering guarantee of all is worth stating out loud, because it is the part that people forget. The results array is in the order of the input array and not in the order that the promises finished, so you can always line the results up with the inputs that produced them.