Sub topic 2
Promise.allSettled, Promise.race, and Promise.any
This chapter assumes you know async functions, await, try/catch, and how Promise.all fails fast. The examples use top-level await, so run them as ES modules (.mjs files in Node.js).
Promise.allSettled: Collect Every Outcome
Promise.all rejects as soon as one input rejects. Promise.allSettled never short-circuits. It waits until every input has settled and then always fulfills. Use it when the tasks are independent and you need a report on each one, such as sending notifications to several services.
Reading Settled Results and Reporting Partial Failure
Each result is an object. Its status is either 'fulfilled', in which case it has a value, or 'rejected', in which case it has a reason. The results come back in input order.
const outcomes = await Promise.allSettled([
Promise.resolve('ok'),
Promise.reject(new Error('failed'))
]);
for (const outcome of outcomes) {
if (outcome.status === 'fulfilled') {
console.log('value:', outcome.value);
} else {
console.log('reason:', outcome.reason.message);
}
}
// value: ok
// reason: failedPromise.race: The First Promise to Settle Decides
Promise.race settles the same way as the first input to settle, whether that input fulfills or rejects. The inputs that finish later are ignored, but they keep running.
Building a Timeout with Promise.race
To add a timeout, race the real work against a promise that rejects after ms milliseconds. Clear the timer in finally. Otherwise it stays scheduled after the race is decided and can keep a Node.js process alive.
async function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`Timed out after ${ms} ms`)), ms);
});
try {
return await Promise.race([promise, timeout]);
} finally {
clearTimeout(timer);
}
}
const slow = new Promise((resolve) => setTimeout(() => resolve('done'), 500));
try {
await withTimeout(slow, 100);
} catch (err) {
console.log(err.message); // Timed out after 100 ms
}Promise.any: The First Fulfillment Wins
Promise.any ignores rejections and fulfills with the first input that succeeds. This makes it a good fit for fallbacks, such as trying several mirrors of the same resource. It rejects only if every input rejects.
const first = await Promise.any([
Promise.reject(new Error('mirror A down')),
new Promise((resolve) => setTimeout(() => resolve('mirror B'), 50))
]);
console.log(first); // mirror BExercise
You query three caches and want the first successful answer, even if a faster cache returns an error. Should you use Promise.race or Promise.any, and why?
Show answer
Use Promise.any. Promise.race would adopt the fast cache's rejection. Promise.any skips rejections and fulfills with the first successful value.
Exercise
Why does withTimeout call clearTimeout in a finally block rather than only after a successful race?
Show answer
The finally block runs whether the race fulfills or rejects. The pending timer is cleared in both cases, so it never fires late or keeps the process alive.