What is the difference between the promise combinators?
They all take an iterable of promises and return a promise, but they differ in when they settle and what they do when one of the inputs fails.
Promise.all waits for every promise to fulfil, and then resolves with an array of the results in the original order. If any of them rejects, the returned promise rejects immediately with that reason, and the other promises keep running but their results are ignored.
Promise.race settles with whichever promise settles first, whether that is a fulfilment or a rejection. It is the tool for implementing a timeout, or for taking the quickest response from several sources.
Promise.allSettled waits for every promise to settle and then resolves with an array describing the outcome of each one, either a status of fulfilled with the value or a status of rejected with the reason. It never rejects, which makes it the right choice when you want to collect several results and handle the failures individually rather than losing all of them.
const ok = (v) => Promise.resolve(v);
const fail = (msg) => Promise.reject(new Error(msg));
Promise.allSettled([ok(1), fail("bad"), ok(3)]).then((results) => {
for (const result of results) {
console.log(result.status, result.value ?? result.reason.message);
}
});The ordering guarantee of all is worth stating, because it is the one people forget. The results array is in the order of the input array, not in the order the promises completed, so you can always line the results up with the inputs that produced them.