Sub topic 6
Failing Fast When the Signal Is Already Aborted
This chapter assumes you know how to create an AbortController, read signal.aborted and signal.reason, and listen for the abort event, all covered in earlier chapters. You should also be comfortable with promises, async/await, and try/catch.
A cancellable function has to handle a case that is easy to miss: the caller passes a signal that was aborted before your function was even called. This chapter explains why that case breaks naive implementations, how to detect it, and where the check belongs.
Why the abort event is not enough
The abort event fires once, at the moment abort() is called. If you attach a listener after that moment, the listener never runs. A signal does not replay past events to new listeners.
const controller = new AbortController();
controller.abort();
controller.signal.addEventListener('abort', () => {
console.log('this never runs');
});
console.log('aborted?', controller.signal.aborted); // trueNow picture a function that relies only on the event:
function naiveDelay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
const timerId = setTimeout(resolve, ms);
signal?.addEventListener('abort', () => {
clearTimeout(timerId);
reject(signal.reason);
}, { once: true });
});
}
const controller = new AbortController();
controller.abort();
naiveDelay(2000, { signal: controller.signal })
.then(() => console.log('resolved after 2 s, despite the abort'))
.catch((err) => console.log('rejected:', err.name));This prints resolved after 2 s, despite the abort. The caller said "cancel" and the function did the full amount of work anyway. With a timer the cost is only wasted time. With a network request, a database write, or a payment call, the cost is real.
The rule: check `aborted` before doing anything
The fix is a synchronous check at the top of the function, before any side effect:
- If there is no signal, carry on. The signal is optional.
- If
signal.abortedistrue, stop at once and reject withsignal.reason. - Otherwise, start the work and subscribe to the
abortevent for later cancellation.
Rejecting with signal.reason, and not with a new error you build yourself, matters. The reason is whatever the caller chose: the default AbortError DOMException, a TimeoutError from AbortSignal.timeout(), or a custom value passed to abort(reason). Passing it through unchanged lets the caller's error handling work the same way whether the abort happened before or during your function.
Two ways to write the check
How you write the check depends on whether your function is async.
Inside an `async` function: `throwIfAborted()`
signal.throwIfAborted() throws signal.reason if the signal is aborted and does nothing otherwise. Inside an async function, any throw becomes a rejected promise, so this one line covers the whole rule:
async function loadUser(id, { signal } = {}) {
signal?.throwIfAborted();
// Simulated work standing in for a real lookup
await new Promise((resolve) => setTimeout(resolve, 100));
return { id, name: 'Ada' };
}
const controller = new AbortController();
controller.abort();
loadUser(42, { signal: controller.signal })
.then((user) => console.log('got', user))
.catch((err) => console.log('rejected early:', err.name)); // "AbortError"The optional chaining (signal?.) keeps the signal optional. Callers who never pass one pay nothing.
Inside a promise executor: check and `return`
When you wrap callback- or timer-based work in new Promise(...), check signal.aborted inside the executor, call reject, and return so the rest of the executor does not run:
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return; // without this, the timer below would still start
}
const timerId = setTimeout(resolve, ms);
signal?.addEventListener('abort', () => {
clearTimeout(timerId);
reject(signal.reason);
}, { once: true });
});
}The return is the part people forget. reject does not stop execution. Without the return, the function rejects correctly but still starts a timer and registers a listener on a signal that will never fire again. The next chapter builds on this delay() and adds the cleanup that runs on success.
You can also call signal?.throwIfAborted() as the first line of the executor. A throw inside a promise executor becomes a rejection, so the result is the same. The explicit if makes it easier to see the return.
The trap: throwing synchronously from a promise-returning function
A function that returns a promise but is not async must never throw synchronously for an aborted signal. Look at this version:
function badDelay(ms, { signal } = {}) {
signal?.throwIfAborted(); // throws before any promise exists
return new Promise((resolve) => setTimeout(resolve, ms));
}
const controller = new AbortController();
controller.abort();
try {
badDelay(1000, { signal: controller.signal })
.catch((err) => console.log('handled in .catch:', err.name));
} catch (err) {
console.log('escaped as a synchronous throw:', err.name);
}The .catch handler never runs, because badDelay threw before it returned a promise. A caller who writes badDelay(...).catch(...) without a surrounding try gets an uncaught exception. The function now fails in two different ways depending on timing, which makes it harder to use than the built-in APIs.
| Function shape | Correct early check | Result for the caller |
|---|---|---|
| `async function` | `signal?.throwIfAborted()` at the top | Rejected promise |
| Returns `new Promise(...)` | `if (signal?.aborted) { reject(signal.reason); return; }` in the executor | Rejected promise |
| Returns a promise, not `async`, check outside the executor | `return Promise.reject(signal.reason)` | Rejected promise |
| Returns a promise, calls `throwIfAborted()` outside any executor | None, this is the bug | Synchronous throw |
Matching platform behavior
Built-in APIs follow this rule. fetch called with an aborted signal returns a promise that rejects with the signal's reason, and it sends no request:
const controller = new AbortController();
controller.abort(new Error('Stale request'));
fetch('https://example.com', { signal: controller.signal })
.catch((err) => console.log(err.message)); // "Stale request"The same goes for addEventListener with an aborted signal option, which adds no listener at all. When your function behaves the same way, callers can treat your API and fetch alike: one .catch, one check of err.name, no special cases.
Placing the check before side effects
"At the top" really means "before the first side effect". Validating arguments first is fine, because validation changes nothing. Anything that changes the outside world must come after the check:
const log = [];
async function saveNote(text, { signal } = {}) {
if (typeof text !== 'string') {
throw new TypeError('text must be a string');
}
signal?.throwIfAborted(); // before anything is written
log.push(`saving: ${text}`); // the side effect
await new Promise((resolve) => setTimeout(resolve, 50));
return log.length;
}
const controller = new AbortController();
controller.abort();
saveNote('hello', { signal: controller.signal })
.catch((err) => console.log(err.name, 'log length:', log.length)); // AbortError log length: 0If the order is reversed, an aborted call still writes to the log. That is a partial effect the caller asked you not to make.
Argument errors and abort errors can arrive in either order. Most platform APIs report invalid arguments first. Pick one order, document it, and keep it the same across your API.
Edge cases worth knowing
- Reused controllers. A controller can only abort once. Once
abortedistrue, it staystrue. Code that keeps one controller for several operations will hit the early-abort path on every call after the first abort. The fix belongs to the caller (create a new controller per operation), but your early check keeps the failure loud and immediate. - Signals that abort between awaits. The early check only covers the moment of the call. A signal can abort after your first
await, so long-running functions need further checks. The chapter on cancellation checkpoints covers this. - A non-signal value. If a caller passes something that is not an
AbortSignal,signal.abortedisundefinedand your check silently passes. If you want strict input checking, testsignal instanceof AbortSignaland throw aTypeError, asfetchdoes. - Falsy reasons.
abort(undefined)stores the defaultAbortError, butabort(0)orabort('')stores those exact values. Always branch onsignal.aborted, never onsignal.reason.
Exercise
This function is supposed to reject immediately for an already-aborted signal. Name two bugs and give a corrected version. function readChunk(source, { signal } = {}) { source.open(); return new Promise((resolve, reject) => { if (signal.aborted) reject(new Error('aborted')); source.once('data', resolve); }); }
Show answer
First, source.open() runs before the abort check, so an aborted call still opens the source. Second, signal.aborted throws a TypeError when no signal is passed, because the signal is optional and should be accessed with signal?.aborted. There are two further problems: the function rejects with a new Error and not with signal.reason, and the missing return lets it register the data listener anyway. Corrected: function readChunk(source, { signal } = {}) { return new Promise((resolve, reject) => { if (signal?.aborted) { reject(signal.reason); return; } source.open(); source.once('data', resolve); }); }
Exercise
You change "async function f({ signal } = {}) { signal?.throwIfAborted(); ... }" into a plain function "function f({ signal } = {}) { signal?.throwIfAborted(); return doWork(); }" where doWork returns a promise. What changes for a caller who writes f({ signal: abortedSignal }).catch(handle)?
Show answer
In the async version the throw becomes a rejected promise, so handle runs. In the plain version throwIfAborted throws synchronously before any promise is returned, so .catch is never attached and the caller gets an uncaught exception. To fix it, keep the function async, or replace the check with: if (signal?.aborted) return Promise.reject(signal.reason);