Sub topic 5
Designing the API: An Optional signal in the Options Object
Before you write any cancellation logic, decide how callers will hand you a signal. This chapter covers that design decision. The rule is short: accept an optional signal property inside an options object. Getting the details right means your function behaves like fetch, addEventListener, and Node's promise-based APIs, so callers don't need to read your docs to cancel it.
This chapter assumes you are comfortable with object destructuring and default parameters, optional chaining (?.), and async/await. The examples run in Node.js 18 or later as ES modules (save them as .mjs). Code that uses fetch or addEventListener also runs in a browser.
The platform convention
Almost every cancellable API in the web platform and in Node.js takes its signal in the same way. The signal goes in an options object, the property is called signal, and it is optional.
| API | Where the signal goes |
|---|---|
| `fetch(url, init)` | `init.signal` |
| `target.addEventListener(type, fn, options)` | `options.signal` |
| `readable.pipeTo(dest, options)` | `options.signal` |
| `fs.promises.readFile(path, options)` (Node) | `options.signal` |
| `setTimeout(ms, value, options)` from `node:timers/promises` | `options.signal` |
| `events.once(emitter, name, options)` (Node) | `options.signal` |
| `navigator.locks.request(name, options, callback)` | `options.signal` |
None of these APIs takes a signal as a positional argument, and none calls it abortSignal, cancelToken, or controller. When you follow the same shape, callers can pass their signal straight through without thinking about it, and you can forward it into these APIs without renaming anything.
The canonical signature
Here is the pattern in a complete, runnable function. It counts down and pauses between numbers, using Node's promise-based timer, which already understands signals:
import { setTimeout as sleep } from 'node:timers/promises';
async function countdown(from, { signal, intervalMs = 100 } = {}) {
for (let n = from; n > 0; n--) {
console.log(n);
await sleep(intervalMs, undefined, { signal });
}
return 'liftoff';
}
// Works with no options at all
console.log(await countdown(3));
// Works with other options and no signal
console.log(await countdown(2, { intervalMs: 50 }));
// Works with a signal
const controller = new AbortController();
setTimeout(() => controller.abort(), 150);
try {
await countdown(10, { signal: controller.signal });
} catch (err) {
console.log('stopped:', err.name); // "stopped: AbortError"
}Each part of the signature has a job:
- The options object comes last. Required inputs (
from) stay positional. Optional settings, the signal included, go in the trailing object. - The
= {}default lets callers leave out the options entirely. Without it,countdown(3)would throwTypeError: Cannot destructure property 'signal' of 'undefined'. - Destructuring
signalwith no default leaves itundefinedwhen the caller doesn't supply one. That is the correct state for "this call cannot be cancelled." - Other options sit next to it.
intervalMshas a default value andsignaldoes not. Both live in the same object, so adding more options later doesn't break any existing call.
The diagram below shows how a call flows through this signature.
Why not a positional parameter?
A signature like countdown(from, signal) looks simpler, but it causes trouble as soon as the function grows:
- If you add a second optional setting, callers who want only that setting have to write
countdown(3, undefined, 50). - The argument's position doesn't tell the reader what it is.
{ signal }describes itself. - Wrapper functions can't forward "all the options" in one step. With an object, they can spread or pass it along.
- It breaks the convention in the table above, so anyone who has used
fetchwill guess wrong.
Accept the signal, not the controller
Take an AbortSignal, never an AbortController. The controller has the power to abort and the signal can only observe. Your function needs to observe cancellation. It has no business triggering it for the caller. If you accept the controller, any code inside your function, or inside a library you pass it to, could call abort() and cancel unrelated work that shares the same controller.
Treat the signal as optional everywhere
Because signal may be undefined, every use of it inside the function has to tolerate that case. Optional chaining makes this short:
function describe({ signal } = {}) {
return {
cancellable: signal !== undefined,
aborted: signal?.aborted ?? false,
};
}
console.log(describe()); // { cancellable: false, aborted: false }
console.log(describe({ signal: AbortSignal.abort() })); // { cancellable: true, aborted: true }Forwarding undefined is also safe. fetch(url, { signal: undefined }) and sleep(ms, value, { signal: undefined }) both behave as if no signal was given. So you can always write { signal } when you call a nested API, with no if around it.
A common mistake is to invent a fallback such as signal = new AbortController().signal. It works, but it creates an object that will never fire, and it hides the difference between "not cancellable" and "cancellable but not yet aborted." Leave the value undefined.
Validating the signal
Built-in APIs reject values that aren't signals. fetch('/x', { signal: 'stop' }) throws a TypeError. If your function is a public API, check the value at the boundary so a wrong argument fails loudly and doesn't get silently ignored:
function validateSignal(signal) {
if (signal === undefined) return;
if (
signal === null ||
typeof signal !== 'object' ||
typeof signal.aborted !== 'boolean' ||
typeof signal.addEventListener !== 'function'
) {
throw new TypeError('options.signal must be an AbortSignal');
}
}
validateSignal(undefined); // ok
validateSignal(new AbortController().signal); // ok
try {
validateSignal(new AbortController()); // the controller, not its signal
} catch (err) {
console.log(err.message); // "options.signal must be an AbortSignal"
}This check tests the object's shape rather than using signal instanceof AbortSignal. instanceof fails for signals created in another realm, such as an iframe or a Node vm context, and it rejects lightweight test doubles. Node's own internal validator also checks shape. For internal helpers, you can usually skip validation entirely.
Forwarding options without clobbering the signal
Wrapper functions often pass their options through to an inner function. When the wrapper substitutes its own signal, the order of properties in the object literal decides which signal wins:
function inner({ signal } = {}) {
return signal?.aborted;
}
function outer(options = {}) {
const mine = AbortSignal.abort();
const wrong = inner({ signal: mine, ...options }); // caller's signal overwrites mine
const right = inner({ ...options, signal: mine }); // mine wins
return { wrong, right };
}
console.log(outer({ signal: new AbortController().signal }));
// { wrong: false, right: true }Put the property you need to force after the spread. Later chapters use this when they combine a caller's signal with a timeout.
Documenting the contract
Callers learn your cancellation behaviour from your documentation and types, so write it down. With JSDoc:
/**
* Counts down from `from`, pausing between numbers.
* @param {number} from
* @param {object} [options]
* @param {AbortSignal} [options.signal] Aborting rejects with signal.reason.
* @param {number} [options.intervalMs=100]
* @returns {Promise<string>}
*/
async function documentedCountdown(from, { signal, intervalMs = 100 } = {}) {
return 'liftoff';
}State in the docs what happens when the signal aborts. The usual answer is that the returned promise rejects with signal.reason. The next chapters build exactly that behaviour.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| No `= {}` default | `TypeError` when the options object is omitted | `function f(x, { signal } = {})` |
| Signal as a positional argument | Awkward `undefined` placeholders, hard to forward | Move it into the options object |
| Naming it `abortSignal` or `cancelToken` | Can't be passed straight through to `fetch` | Name it `signal` |
| Accepting the controller | Callees can cancel the caller's other work | Accept `controller.signal` only |
| `signal.aborted` without `?.` | Crash when no signal is passed | Use `signal?.aborted` |
| Spreading options after your own `signal` | Your signal is silently replaced | Spread first, then set `signal` |
Exercise
A colleague writes async function upload(file, signal, retries = 3) and calls it as upload(f, undefined, 5). Rewrite the signature to follow platform conventions, and show the new call that sets retries to 5 with no signal.
Show answer
async function upload(file, { signal, retries = 3 } = {}). The call becomes upload(f, { retries: 5 }). The signal is an optional property of a trailing options object, the = {} default lets callers omit the object, and signal stays undefined when it isn't supplied.
Exercise
A wrapper calls inner({ signal: deadlineSignal, ...options }), but its deadline never fires when callers pass their own signal. Why, and what is the fix?
Show answer
Object spread copies properties in order, so the caller's options.signal overwrites deadlineSignal. Put the spread first and the forced property last: inner({ ...options, signal: deadlineSignal }). If the caller's signal should also still work, combine the two signals (covered in the chapter on AbortSignal.any()) and pass the combined signal.