Sub topic 5
Designing the API: An Optional signal in the Options Object
This chapter assumes you know object destructuring with default values, optional chaining (?.), and the basic split between AbortController and AbortSignal from the earlier chapters. The goal is to choose a function signature that callers will recognize as soon as they see it.
The Platform Convention
Built-in APIs that support cancellation all accept the signal in the same way. It goes in an options object as a property named signal, and it is optional.
| API | How it accepts a signal |
|---|---|
| `fetch` | `fetch(url, { signal })` |
| `addEventListener` | `el.addEventListener(type, fn, { signal })` |
| `ReadableStream.pipeTo` | `readable.pipeTo(dest, { signal })` |
| Node `timers/promises` | `setTimeout(ms, value, { signal })` |
| Node `fs/promises` | `readFile(path, { signal })` |
If your own functions follow this shape, callers can pass one signal through a whole call chain without looking anything up. The next chapters build on this.
Why the Signal Goes in an Options Object
You could add signal as a positional parameter, as in delay(ms, signal). Avoid that. An options object has these advantages:
- Callers who don't need cancellation leave it out, and they never have to write
undefinedas a placeholder. - You can add
timeoutMs,retries, or other settings later without breaking existing calls. { signal }at the call site makes it obvious what the argument is.
Why You Accept a Signal, Not a Controller
The caller owns the AbortController, and your function receives only the AbortSignal. This split is deliberate. A signal can be observed but cannot trigger an abort, so your function can't cancel work behind the caller's back. One controller's signal can also be handed to many functions at once.
Writing the Signature
Destructure signal from the options and default the whole object to {}. Then the function works when called with no options at all. Inside the function, use signal?. wherever you touch the signal, because it may be undefined.
function describeCall(label, { signal } = {}) {
if (signal !== undefined && !(signal instanceof AbortSignal)) {
throw new TypeError('options.signal must be an AbortSignal');
}
const state = signal?.aborted ?? 'no signal';
return `${label}: aborted = ${state}`;
}
const controller = new AbortController();
console.log(describeCall('no options')); // aborted = no signal
console.log(describeCall('with signal', { signal: controller.signal })); // aborted = false
controller.abort();
console.log(describeCall('after abort', { signal: controller.signal })); // aborted = trueThe instanceof check is optional, and Node's built-ins do the same thing. It turns a mistake like passing the controller instead of its signal into a clear TypeError. Without the check, the function would quietly do nothing on abort.
Common Mistakes
- Making
signalrequired. Cancellation should be opt-in, the same as infetch. - Passing the controller around. Pass the signal and keep the controller with whoever decides when to cancel.
- Inventing names such as
abortSignalorcancelToken. Usesignalso that{ signal }can be forwarded to other APIs unchanged. - Calling
signal.abortedwithout?.. This crashes when no signal was given.
Exercise
Rewrite function search(query, signal, limit) so it follows the platform convention, keeps limit defaulting to 10, and works when called as search('cats').
Show answer
function search(query, { signal, limit = 10 } = {}) { ... }. Both settings move into one optional options object, destructured with a default of {}. Inside the body, use signal?. because the signal may be undefined.
Exercise
Why should a cancellable function accept an AbortSignal instead of an AbortController?
Show answer
A signal can be observed but cannot trigger an abort. The function can react to cancellation but cannot cancel on the caller's behalf. The caller keeps sole control and can share one signal across many calls.