Sub topic 4
Reacting to the abort Event
In the previous chapter, your function read signal.aborted and signal.reason at a moment it chose. That approach covers checks at the start of a function or between steps. It does nothing for work that is waiting, such as a pending timer, an open socket, or a callback that has not fired yet. Your code is not running while that work waits, so it never gets the chance to read signal.aborted. For those cases, the signal has to notify you, and it does so with the abort event.
This chapter assumes you know JavaScript closures, promises, and addEventListener. All examples run in Node.js 18 or later and in modern browsers.
AbortSignal Is an EventTarget
AbortSignal inherits from EventTarget, the same base class that DOM elements and window use. You subscribe to it the same way you subscribe to a button click:
const controller = new AbortController();
const { signal } = controller;
signal.addEventListener('abort', (event) => {
console.log('event type:', event.type); // "abort"
console.log('target is signal:', event.target === signal); // true
console.log('aborted:', signal.aborted); // true
console.log('reason:', signal.reason.name); // "AbortError"
}, { once: true });
controller.abort();The listener gets a plain Event object, and the reason is not stored on it. To find out why the signal aborted, read signal.reason (or event.target.reason). By the time any listener runs, the signal has already been updated, so aborted is true and reason holds its final value.
addEventListener versus onabort
The signal also has an onabort property, which works like button.onclick. Both are valid, but they behave differently in reusable code.
| Feature | `addEventListener('abort', fn)` | `signal.onabort = fn` |
|---|---|---|
| Number of handlers | Any number | One; assigning again replaces the previous one |
| Removal | `removeEventListener` or the `signal` option | Assign `null` |
| Supports `{ once: true }` | Yes | No |
| Safe in library code | Yes | No; it can overwrite the caller's handler |
Inside a function that receives a signal from its caller, always use addEventListener. The caller and other functions may share the same signal. If your function sets onabort, it silently replaces whatever handler they installed.
When and How Listeners Run
Several timing rules decide whether a cancellable function behaves correctly. The next example shows all of them.
const controller = new AbortController();
const { signal } = controller;
signal.addEventListener('abort', () => {
console.log('listener 1, aborted =', signal.aborted);
});
signal.onabort = () => console.log('onabort handler');
signal.addEventListener('abort', () => console.log('listener 2'));
console.log('before abort()');
controller.abort();
console.log('after abort()');
controller.abort(); // second call: nothing happens
console.log('done');Output:
before abort()
listener 1, aborted = true
onabort handler
listener 2
after abort()
doneThe output shows four rules.
- Dispatch is synchronous.
controller.abort()returns only after every listener has finished. The listeners do not wait for a later tick of the event loop. - Listeners run in registration order. The
onaborthandler takes the position in the list where it was first assigned. - State is updated before dispatch. Each listener already sees
aborted === trueand the finalreason. - The event fires at most once. A signal never goes back to the not-aborted state. Calling
abort()again does nothing: the reason stays the same and no event fires.
The sequence below shows what happens inside one abort() call.
Consequences of synchronous dispatch
Because listeners run inside the caller's abort() call, they should do as little as possible: clear a timer, close a handle, reject a promise. Any heavy work in a listener delays the code that called abort().
Rejecting a promise from inside a listener is safe. The rejection is queued, so .catch handlers and await continuations run later as microtasks, after abort() has returned and the current synchronous code has finished.
Listeners Added Too Late Never Fire
The abort event fires once, at the moment of abort. A listener attached to a signal that is already aborted will never be called, and no error tells you so.
const controller = new AbortController();
controller.abort();
controller.signal.addEventListener('abort', () => {
console.log('this never prints');
});
console.log('aborted already:', controller.signal.aborted); // trueThis is the most common bug in hand-written cancellation code. A function that only subscribes to the event will hang forever when the caller passes a signal that was aborted earlier. The fix is to combine the two techniques you have seen so far: check the state first, then subscribe.
function whenAborted(signal, callback) {
if (signal.aborted) {
callback(signal.reason);
return () => {};
}
const listener = () => callback(signal.reason);
signal.addEventListener('abort', listener, { once: true });
return () => signal.removeEventListener('abort', listener);
}
// Usage
const controller = new AbortController();
const stop = whenAborted(controller.signal, (reason) => {
console.log('cancelled:', reason.name);
});
controller.abort(); // prints "cancelled: AbortError"
stop(); // safe to call even after the listener has runThe helper calls callback in both cases: right away when the signal is already aborted, and later when it aborts. It also returns an unsubscribe function, which you will need once the work finishes normally. A later chapter covers that cleanup in detail. Rejecting early with an already-aborted signal also gets its own chapter. For now, the rule is simple: never rely on the event alone.
Why once: true Matters
The event fires at most once, so { once: true } might look unnecessary. It still does something useful. After the listener runs, the signal drops its reference to it. A listener is usually a closure over your function's state, such as timer IDs, buffers, and resolve/reject functions. Without once, an aborted signal that stays alive (for example, one stored on a long-lived object) keeps all of that state in memory.
once only removes the listener when the event fires. If the work finishes and the signal never aborts, the listener stays attached until you remove it yourself. That is why the whenAborted helper above returns an unsubscribe function.
Errors Thrown Inside a Listener
An exception thrown by an abort listener does not reach the code that called abort(). The runtime reports it as an uncaught error, and dispatch continues with the remaining listeners.
const controller = new AbortController();
controller.signal.addEventListener('abort', () => {
throw new Error('listener failed');
});
controller.signal.addEventListener('abort', () => {
console.log('second listener still runs');
});
try {
controller.abort();
console.log('abort() returned normally');
} catch {
console.log('never reached');
}In a browser, the error shows up in the console and fires the error event on window. In Node.js, it is raised as an uncaught exception, which ends the process by default. In both cases, the try/catch around abort() never catches it.
This leads to two rules:
- Do not throw from an abort listener to signal cancellation. Reject a promise or call an error callback instead.
- Wrap cleanup code that might throw, such as closing a resource that is already closed, in its own
try/catchinside the listener.
Choosing Between Polling and the Event
Both techniques read the same signal. They suit different kinds of work.
| Situation | Use |
|---|---|
| Your code runs in steps and can check between them | Read `signal.aborted` or call `throwIfAborted()` |
| Your code is waiting for a timer, callback, or external resource | Listen for `abort` |
| Your function is starting and the signal may already be aborted | Check `signal.aborted` first, then listen |
| You pass the signal to an API that accepts one, such as `fetch` | Neither; that API handles it |
Most real cancellable functions combine these: one check on entry, one listener while waiting, and removal of that listener on completion. The next chapters build exactly that structure.
Exercise
A function calls signal.addEventListener('abort', () => reject(signal.reason)) and does nothing else with the signal. A caller writes const c = new AbortController(); c.abort(); await myFn({ signal: c.signal });. What happens, and how do you fix it?
Show answer
The promise never settles. The signal aborted before the listener was attached, and the abort event fires only once, at the moment of abort, so the listener is never called. Fix it by checking signal.aborted first and rejecting immediately with signal.reason. Attach the listener only when the signal is not yet aborted.
Exercise
Predict the output order: signal.addEventListener('abort', () => console.log('A')); Promise.resolve().then(() => console.log('B')); controller.abort(); console.log('C');
Show answer
A, C, B. The abort listener runs synchronously inside abort(), so A prints first. The rest of the synchronous code then prints C. The promise callback is a microtask, so B prints only after the current synchronous code finishes.
Exercise
Why should a library function use addEventListener rather than signal.onabort = ..., and what does { once: true } add when the event can only fire once anyway?
Show answer
onabort holds a single handler, so assigning it would replace a handler the caller or another function set on the shared signal. addEventListener adds a listener without removing others. { once: true } makes the signal release its reference to the listener after dispatch, so the closure and the state it captures can be garbage-collected even if the signal object stays alive.