Sub topic 3
Reading a Signal: aborted and reason
An AbortSignal is a small object that answers two questions for any code holding it: has cancellation been requested, and why? It answers them through two read-only properties, aborted and reason. Every cancellable function you write in this tutorial reads these properties, so you need to know exactly what they contain at each moment, how they change, and where they can trip you up.
This chapter assumes you know JavaScript functions and destructuring, promises with async/await, and try/catch. You should also have created an AbortController and called abort() on it, as in the previous chapter. The code runs in any modern browser and in Node.js 18 or later.
The two properties
signal.aborted is a boolean. It is false when the signal is created. It becomes true when the controller's abort() method is called, and it never goes back to false.
signal.reason holds the value that explains the abort. Before the abort it is undefined. After the abort it holds whatever was passed to abort(). If nothing was passed, it holds a DOMException whose name is "AbortError".
const controller = new AbortController();
const { signal } = controller;
console.log(signal.aborted); // false
console.log(signal.reason); // undefined
controller.abort();
console.log(signal.aborted); // true
console.log(signal.reason instanceof DOMException); // true
console.log(signal.reason.name); // "AbortError"
console.log(signal.reason.message); // e.g. "This operation was aborted"The exact message text varies between browsers and Node.js. Never test against it. The name property is the stable part.
| Moment | `signal.aborted` | `signal.reason` |
|---|---|---|
| After `new AbortController()` | `false` | `undefined` |
| After `controller.abort()` | `true` | `DOMException` named `"AbortError"` |
| After `controller.abort(value)` | `true` | `value`, exactly as passed |
| After a second `abort(other)` call | `true` | Unchanged from the first abort |
A signal changes state once
A signal has exactly two states, and the only transition goes from "not aborted" to "aborted". Later calls to abort() do nothing. They do not replace the reason, and they do not fire the abort event again.
The first abort wins, which is easy to show:
const controller = new AbortController();
controller.abort(new Error('first'));
controller.abort(new Error('second'));
console.log(controller.signal.reason.message); // "first"This matters when several parts of a program share one controller. A user's cancel button and a cleanup routine might both call abort(). Whichever runs first decides the reason that every consumer sees. If you need to know which source cancelled the work, give each source a distinct reason, and accept that later callers cannot overwrite it.
The properties are read-only
Only the controller can change a signal. The signal's properties are getters with no setters. In strict mode code, including ES modules and class bodies, assigning to them throws a TypeError. In sloppy mode the assignment is silently ignored.
'use strict';
const { signal } = new AbortController();
try {
signal.aborted = true;
} catch (err) {
console.log(err instanceof TypeError); // true
}
console.log(signal.aborted); // falseThis split is the reason the API has two objects. You hand the signal to code you call, and that code can observe cancellation but cannot cause it. You keep the controller, so the power to cancel stays with the caller.
Pre-aborted signals with AbortSignal.abort()
You don't always need a controller to get an aborted signal. The static method AbortSignal.abort(reason) returns a signal that is already in the aborted state:
const signal = AbortSignal.abort();
console.log(signal.aborted); // true
console.log(signal.reason.name); // "AbortError"
const custom = AbortSignal.abort(new Error('Not allowed'));
console.log(custom.reason.message); // "Not allowed"These signals are mostly useful in tests and for passing a "cancelled from the start" signal into a function. A later chapter covers how your functions should react when they receive one.
Which property to check
Use aborted to decide whether cancellation has happened. Use reason to decide what to report. Mixing these up causes the most common bug with signals.
The reason can be any value: an Error, a string, a number, or even null. Code that checks reason for truthiness breaks when the reason is falsy:
const controller = new AbortController();
controller.abort(0); // unusual, but legal
const { signal } = controller;
if (signal.reason) {
console.log('never printed: 0 is falsy');
}
if (signal.aborted) {
console.log('aborted, reason is', signal.reason); // aborted, reason is 0
}There is a related edge case. abort(undefined) counts as calling abort() with no argument, so the reason becomes the default AbortError. abort(null), by contrast, stores null as the reason. If you ever see null in signal.reason, someone passed it on purpose.
Passing the reason along unchanged is what built-in APIs do. When fetch is cancelled, it rejects with signal.reason. Your functions should do the same, so callers see the reason they chose. The chapter on abort reasons covers AbortError, TimeoutError, and custom reasons in detail.
Reading state from a function that may have no signal
Your functions will accept the signal as optional. When the caller doesn't pass one, signal is undefined, and optional chaining keeps the checks safe:
function status({ signal } = {}) {
if (signal?.aborted) {
return `cancelled: ${String(signal.reason)}`;
}
return 'running';
}
console.log(status()); // "running"
console.log(status({ signal: new AbortController().signal })); // "running"
console.log(status({ signal: AbortSignal.abort('stop') })); // "cancelled: stop"signal?.aborted evaluates to undefined when there is no signal, and undefined is falsy, so the function proceeds normally.
A reading is a snapshot
Reading signal.aborted tells you the state at that instant. JavaScript runs on a single thread, so the value cannot change while your synchronous code runs. It can change at every await, because other code, such as a click handler or a timer that calls abort(), gets a chance to run while your function is paused.
async function work({ signal } = {}) {
console.log('before await:', signal.aborted); // false
await new Promise((resolve) => setTimeout(resolve, 100));
console.log('after await:', signal.aborted); // true
}
const controller = new AbortController();
work({ signal: controller.signal });
setTimeout(() => controller.abort(), 50);A check at the top of a function says nothing about the state after its first await. You have two ways to respond to aborts that happen later. You can read the state again at points you choose, or you can be notified the moment the abort occurs. The next chapter covers notification through the abort event. Repeated checks inside loops come later, with throwIfAborted().
Common mistakes
| Mistake | Why it fails | Fix |
|---|---|---|
| `if (signal.reason)` to detect abort | The reason may be falsy (`0`, `''`, `null`) | Check `signal.aborted` |
| Comparing `reason.message` to a string | Message text differs across runtimes | Compare `reason.name`, or the exact reason object |
| Checking `aborted` once at the start of an async function | State can change at any `await` | Listen for `abort`, or check again after awaits |
| Expecting a second `abort()` to update the reason | The first abort is final | Choose the reason at the first abort |
| Creating a new `AbortError` instead of using `reason` | Hides the caller's custom reason | Reject or throw `signal.reason` |
Exercise
A controller runs controller.abort() and then controller.abort(new Error('late')). What do signal.aborted and signal.reason.name contain afterwards, and why?
Show answer
signal.aborted is true and signal.reason.name is "AbortError". The first abort() call had no argument, so it set the default DOMException reason. A signal changes state only once, so the second call has no effect and does not replace the reason.
Exercise
A teammate writes if (signal && signal.reason) return Promise.reject(signal.reason); to bail out of cancelled work. Name an input that slips past this check, and rewrite the condition.
Show answer
AbortSignal.abort(0), AbortSignal.abort(''), or AbortSignal.abort(null) each produce an aborted signal with a falsy reason, so the check passes and the work runs anyway. Use if (signal?.aborted) return Promise.reject(signal.reason);.
Exercise
An async function checks signal.aborted on its first line, finds it false, then awaits a 2-second operation and writes results to storage. The user cancels after 1 second, and the write still happens. Explain the cause.
Show answer
Reading signal.aborted gives a snapshot of that moment. The abort happened during the await, after the only check, and nothing re-read the state before the write. The function has to check signal.aborted again after the await, or react to the abort event, before it does the write.