Sub topic 10
Cancellation with AbortSignal
Assume you know TypeScript functions, generics, promises, async/await, and union-type narrowing. This chapter shows how to pass cancellation through asynchronous code without losing its types.
What cancellation means
An AbortSignal is a read-only object that reports whether an operation has been cancelled. An AbortController owns the cancellation action. Its abort() method changes the controller's signal to the aborted state.
Cancellation is cooperative. The signal does not stop arbitrary JavaScript code. An API must listen to the signal and stop its own work. The browser fetch function supports this protocol.
The signal is usually an optional parameter:
async function fetchText(
url: string,
signal?: AbortSignal
): Promise<string> {
const response = await fetch(url, { signal });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.text();
}The return type is still Promise<string>. Cancellation does not create a special promise type. It causes the promise to reject, just as another runtime failure would.
Handling an aborted operation
Callers create the controller and pass its signal to the function. The controller can also impose a time limit.
async function loadPage(): Promise<void> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5_000);
try {
const text = await fetchText(
"https://example.com",
controller.signal
);
console.log(text.length);
} catch (error: unknown) {
if (error instanceof DOMException && error.name === "AbortError") {
console.log("The request was cancelled.");
} else if (error instanceof Error) {
console.error(`The request failed: ${error.message}`);
} else {
console.error("The request failed with an unknown value.");
}
} finally {
clearTimeout(timer);
}
}The catch variable is unknown under strict TypeScript settings. Narrow it before reading name or message.
Newer runtimes also provide AbortSignal.timeout:
async function fetchWithTimeout(url: string): Promise<string> {
const signal = AbortSignal.timeout(5_000);
return fetchText(url, signal);
}A timeout usually appears as an abort-related error, but exact error classes can vary between browsers and runtimes. Use the runtime's documented behavior when you need to distinguish a user cancellation from a timeout.
Passing cancellation through layers
A useful rule is to accept a signal at every layer that waits on a cancellable operation. The outer function can then pass the same signal downward.
interface User {
id: number;
name: string;
}
async function getUser(
id: number,
signal?: AbortSignal
): Promise<User> {
const response = await fetch(`/api/users/${id}`, { signal });
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data: unknown = await response.json();
if (
typeof data !== "object" ||
data === null ||
!("id" in data) ||
!("name" in data) ||
typeof data.id !== "number" ||
typeof data.name !== "string"
) {
throw new Error("Invalid user response");
}
return { id: data.id, name: data.name };
}
async function showUser(
id: number,
signal?: AbortSignal
): Promise<void> {
const user = await getUser(id, signal);
console.log(user.name);
}The signal only controls operations that receive it. If showUser calls another asynchronous function that ignores the signal, that function may continue after cancellation.
Choosing a cancellation design
| Design | Use it when | TypeScript concern |
|---|---|---|
| Optional `signal?: AbortSignal` | Cancellation is useful but not required | Callers may omit the signal |
| Required `signal: AbortSignal` | The operation must be cancellable | Every caller must provide one |
| `AbortSignal.timeout(ms)` | A fixed deadline is enough | Runtime support must exist |
| Caller-owned controller | A UI action or workflow controls lifetime | The caller must call `abort()` |
Do not treat cancellation as a successful value unless your application explicitly chooses that convention. Most promise-based APIs reject, so callers should handle the rejection.
Exercise
Why does adding signal?: AbortSignal to a function not automatically cancel its work?
Show answer
The function must pass the signal to an API that supports cancellation, such as fetch, or check signal.aborted itself. The type records the available cancellation mechanism, but runtime code must use it.