Sub topic 6
Failing Fast When the Signal Is Already Aborted
This chapter assumes you know promises and async/await. It also assumes you have read the earlier chapters on signal.aborted, signal.reason, the abort event, and the { signal } options convention.
A caller can pass in a signal that has already been aborted. This happens more often than you might expect. A user clicks "Cancel" while a retry loop is waiting between attempts. A component unmounts just before an effect calls your function. A shared controller was aborted by an earlier step in a pipeline. Your function should notice this right away and refuse to start.
Why the abort listener is not enough
The abort event fires once, at the moment abort() is called. A listener you add after that point never runs:
const controller = new AbortController();
controller.abort();
controller.signal.addEventListener('abort', () => {
console.log('this never runs');
});
console.log('aborted?', controller.signal.aborted); // trueSuppose your function relies only on an abort listener and receives an already-aborted signal. It starts the work, waits for an event that never comes, and runs to completion as if nobody had cancelled it. The fix is to check the signal's state before doing anything.
The early check
Check before you allocate timers, open connections, or touch shared state:
function loadConfig(path, { signal } = {}) {
if (signal?.aborted) {
return Promise.reject(signal.reason);
}
return new Promise((resolve) => {
setTimeout(() => resolve({ path, debug: false }), 100);
});
}
const controller = new AbortController();
controller.abort();
loadConfig('app.json', { signal: controller.signal })
.catch((err) => console.log('rejected with:', err.name)); // "AbortError"The check follows three rules:
- Optional chaining (
signal?.aborted) keeps the function working when no signal is passed. - Rejecting with
signal.reasongives the caller exactly the value the aborter chose, whether that is the defaultAbortError, aTimeoutError, or a custom error. - No work starts, so there is nothing to clean up.
In an async function you can write the same check as signal?.throwIfAborted(). A throw inside an async function turns into a rejected promise automatically:
async function loadConfigAsync(path, { signal } = {}) {
signal?.throwIfAborted();
// ...real work here
return { path, debug: false };
}Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Throwing synchronously from a non-async function that returns a promise | Callers using `.catch()` miss the error, and it escapes as an exception | Return `Promise.reject(signal.reason)` |
| Rejecting with `new Error('aborted')` | The caller loses the reason, and `err.name` checks fail | Reject with `signal.reason` |
| Checking after starting a timer or request | The work runs anyway or leaks | Put the check first |
| Writing `signal.aborted` without `?.` | A `TypeError` is thrown when no signal is given | Use `signal?.aborted` |
Exercise
This function is meant to fail fast, but a caller who uses .then().catch() sees an uncaught exception when passing an aborted signal. Why, and how do you fix it?
function fetchUser(id, { signal } = {}) {
signal?.throwIfAborted();
return fetch(/users/${id}, { signal }).then((r) => r.json());
}
Show answer
fetchUser is not async, so throwIfAborted() throws synchronously before any promise exists, and .catch() never sees it. You can fix it in either of two ways. Mark the function async so the throw becomes a rejection, or replace the line with if (signal?.aborted) return Promise.reject(signal.reason);.
Exercise
A caller runs controller.abort(new Error('Logged out')) and then calls loadConfig('a.json', { signal: controller.signal }). What does the returned promise reject with?
Show answer
It rejects with the same Error object whose message is "Logged out", because the early check rejects with signal.reason.