Sub topic 3
Abort Reasons, Deadlines, and Testing
This chapter assumes you already have a cancellable delay() and fetchAll() from the earlier chapters, and that you are comfortable with try/catch and async/await.
Abort Reasons: AbortError, TimeoutError, and Custom Reasons
When a signal aborts, signal.reason says why. Calling abort() with no argument sets the reason to a DOMException named "AbortError". AbortSignal.timeout() uses a DOMException named "TimeoutError". If you pass a value to abort(), that value becomes the reason. throwIfAborted() throws that same value.
const controller = new AbortController();
controller.abort(new Error('User navigated away'));
console.log(controller.signal.reason.message); // "User navigated away"
try {
controller.signal.throwIfAborted();
} catch (err) {
console.log(err.message); // "User navigated away"
}Handling Cancellation in the Caller
Callers should check err.name. If the caller cancelled the work on purpose, that is usually not a failure. Rethrow everything else.
| `err.name` | Meaning | Typical handling |
|---|---|---|
| `AbortError` | Caller cancelled | Ignore quietly |
| `TimeoutError` | Deadline passed | Retry or report a timeout |
| anything else | Real failure | Rethrow or log |
Deadlines and Combined Signals
AbortSignal.timeout(ms) returns a signal that aborts on its own after ms milliseconds. AbortSignal.any([...]) returns a signal that aborts as soon as any of its input signals aborts, and it takes that signal's reason.
async function fetchJson(url, { signal, timeoutMs = 5000 } = {}) {
const timeoutSignal = AbortSignal.timeout(timeoutMs);
const combined = signal
? AbortSignal.any([signal, timeoutSignal])
: timeoutSignal;
try {
const response = await fetch(url, { signal: combined });
return await response.json();
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error(`Timed out after ${timeoutMs} ms`, { cause: err });
}
throw err;
}
}Using a Signal to Remove Event Listeners
addEventListener accepts a signal option. When that signal aborts, the listener is removed, so you don't need to keep a reference to the handler.
const controller = new AbortController();
window.addEventListener('resize', () => console.log('resized'), {
signal: controller.signal,
});
controller.abort(); // listener removedTesting That Your Functions Really Cancel
Write one test for a signal that is already aborted and one for a signal that aborts while the work is running.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { delay } from './delay.js';
test('rejects at once with an already-aborted signal', async () => {
await assert.rejects(delay(1000, { signal: AbortSignal.abort() }), {
name: 'AbortError',
});
});
test('rejects with the custom reason mid-flight', async () => {
const controller = new AbortController();
const reason = new Error('stop');
const pending = delay(1000, { signal: controller.signal });
controller.abort(reason);
await assert.rejects(pending, (err) => err === reason);
});Exercise
A caller passes its own signal to fetchJson and then aborts it. What does err.name show, and why isn't the request treated as a timeout?
Show answer
It shows "AbortError". AbortSignal.any() takes its reason from whichever input aborted first. Here that is the caller's signal, so the TimeoutError branch is skipped and the AbortError is rethrown.