Sub topic 5
Fail-Fast: The First Rejection Wins, the Rest Keep Running
This chapter assumes you know how Promise.all collects results in input order, and that you are comfortable with async/await, try/catch, and timers made with setTimeout. The examples use top-level await, so run them as ES modules: save the file with a .mjs extension and run it with Node 18 or later.
Promise.all has a short-circuit rule. As soon as any input rejects, the returned promise rejects with that reason. It does not wait for the other inputs. This rule is called fail-fast. It is usually what you want. It also causes two kinds of bugs: work keeps happening after you have stopped waiting for it, and results you could have used are thrown away.
What "First" Means
"First" means first in time, not first in the array. The array order affects only where each value goes in the result array when everything fulfills. When there is a rejection, the reason you receive belongs to whichever input rejected earliest.
const start = Date.now();
const log = (msg) => console.log(`${String(Date.now() - start).padStart(4)} ms: ${msg}`);
function task(name, ms, fail = false) {
return new Promise((resolve, reject) => {
setTimeout(() => {
log(`${name} finished`);
if (fail) reject(new Error(`${name} failed`));
else resolve(name);
}, ms);
});
}
try {
await Promise.all([
task('A', 300),
task('B', 100, true),
task('C', 200, true)
]);
log('all fulfilled');
} catch (err) {
log(`caught: ${err.message}`);
}The output is roughly:
100 ms: B finished
100 ms: caught: B failed
200 ms: C finished
300 ms: A finishedThe output shows three things:
- The
catchblock runs at about 100 ms, as soon as B rejects. You never learn that C also failed. - C and A still run to completion. Their timers fire and their logs print after the
catchblock has run. - The process does not exit until about 300 ms, because A's timer keeps the event loop alive.
Why the Later Rejection Is Not "Unhandled"
C rejects after Promise.all has already settled, yet Node does not report an unhandled rejection. The reason is that Promise.all attaches its own handlers to every input when you call it. Once a promise has a handler, its rejection counts as handled, even if that handler now does nothing because the combined promise has already settled. A promise can settle only once, so C's later rejection has no effect on it.
This is useful because you don't get crash noise from losers you no longer care about. It is also a risk, because C's error disappears silently. If C failed for a reason you would want to log, such as a bad credential or a corrupt file, nothing reports it.
The Rest Keep Running
A promise represents a result that is on its way. It is not a handle that can stop the work. Promise.all cannot reach into a fetch, a database driver, or a timer and stop it. When it rejects, every other operation continues, including its side effects.
This matters most for writes. Imagine saving a batch of records:
const db = new Map();
function saveRecord(record, ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (!record.id) return reject(new Error('record is missing an id'));
db.set(record.id, record);
resolve(record.id);
}, ms);
});
}
try {
await Promise.all([
saveRecord({ id: 1, name: 'Ada' }, 150),
saveRecord({ name: 'no id' }, 50),
saveRecord({ id: 3, name: 'Lin' }, 100)
]);
} catch (err) {
console.log('save failed:', err.message);
console.log('records stored right now:', db.size); // 0
}
await new Promise((resolve) => setTimeout(resolve, 200));
console.log('records stored a moment later:', db.size); // 2The caller sees "save failed" and might tell the user nothing was saved. Two records still get written after the error has been reported. If the caller retries the whole batch, those records may be written twice.
Here are the common consequences:
| Situation | What goes wrong after fail-fast |
|---|---|
| Parallel writes | Some writes succeed after you have reported failure, which leaves a partial state |
| Paid API calls | You are billed for requests whose results you discard |
| Cleanup in `catch` or `finally` | Cleanup runs while other tasks still use the resource, such as a temp directory or a connection |
| Retrying the batch | Tasks from the first attempt overlap with the retry |
| Short-lived scripts | The process stays alive until the leftover tasks finish |
Waiting for the Stragglers Before Cleaning Up
Sometimes you want fail-fast semantics for the result but must not clean up until everything has stopped. One way to get both is to rethrow the first error only after waiting for every input:
async function allThenSettle(promises) {
const list = [...promises];
try {
return await Promise.all(list);
} catch (err) {
await Promise.allSettled(list); // wait for the rest; never rejects
throw err;
}
}The iterable is copied into an array first because it is consumed twice, and a generator can only be iterated once. The caller still gets the first rejection reason, but now gets it only after nothing else is running, so a finally block can safely close the connection. The cost is latency: on failure you wait as long as the slowest task. Promise.allSettled gets its own chapter. Actually stopping the stragglers early needs AbortController, which a later chapter covers.
A Related Trap: Starting Promises and Awaiting Them One by One
Fail-fast with Promise.all is safe in one respect: every input has a handler from the start. Code that starts several promises and then awaits them one at a time does not have that protection.
function task(name, ms, fail = false) {
return new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error(`${name} failed`)) : resolve(name)), ms)
);
}
async function loadPage() {
const user = task('user', 200);
const prefs = task('prefs', 50, true);
const u = await user; // still waiting here when prefs rejects at 50 ms
const p = await prefs; // too late: a handler is attached only now
return [u, p];
}
loadPage().catch((err) => console.log('caught:', err.message));At 50 ms prefs rejects, and no handler is attached to it yet, because the function is still suspended at await user. Node reports an unhandled rejection. Since Node 15 the default --unhandled-rejections=throw mode makes that crash the process before your .catch runs. Browsers log an "Uncaught (in promise)" error to the console.
The fix is to hand both promises to a combinator straight away:
async function loadPage() {
const [u, p] = await Promise.all([task('user', 200), task('prefs', 50, true)]);
return [u, p];
}Now the rejection at 50 ms reaches your catch normally, and it arrives sooner, because you don't wait for user first.
When Fail-Fast Is the Right Choice
Fail-fast fits when the tasks only make sense together. Loading a user, their permissions, and their settings to render a page is an example: if any of them fails, the page cannot render, and waiting longer for the others gains nothing. It is a poor fit when the tasks are independent and partial results have value, such as sending notifications to fifty users. In that case you want every outcome, which is what Promise.allSettled gives you.
Before you rely on Promise.all's rejection, ask these questions:
- Do the remaining tasks have side effects that must not happen after a failure? If so, plan for cancellation.
- Does cleanup depend on all tasks having stopped? If so, wait for them to settle before cleaning up.
- Would the other errors or values be useful? If so, use
Promise.allSettledinstead.
Exercise
Promise.all receives three tasks: X fulfills after 400 ms, Y rejects with "Y failed" after 300 ms, and Z rejects with "Z failed" after 150 ms. What reason does the combined promise reject with, at about what time, and do X and Y still finish?
Show answer
It rejects with "Z failed" at about 150 ms, because Z is the first input to reject in time. Its position in the array does not matter. Y still rejects at 300 ms and X still fulfills at 400 ms. Promise.all ignores both results and the program cannot get them from the error it caught.
Exercise
In the first example, task C rejects at 200 ms, after Promise.all has already rejected. Why does Node not report an unhandled rejection for C?
Show answer
Promise.all attached a rejection handler to every input when it was called, so C's rejection counts as handled. The handler does nothing useful because the combined promise has already settled and cannot change state, so C's error is discarded silently.
Exercise
A function runs const a = fetchA(); const b = fetchB(); return [await a, await b];. fetchB rejects quickly while fetchA is slow. What can happen in Node 18, and how do you fix it?
Show answer
b rejects while the function is suspended at await a, and at that moment b has no handler attached. Node reports an unhandled rejection, which crashes the process in the default throw mode. To fix it, write return await Promise.all([fetchA(), fetchB()]); so both promises get handlers immediately.