Sub topic 10
Cancellation with AbortSignal
A promise has no cancel method. Once the work behind it starts, the promise only settles. TypeScript has no special "cancellable" type either. Cancellation is a convention built from two standard objects, AbortController and AbortSignal, and the type system helps with the plumbing around them. This chapter covers how to type that plumbing, how to react to an abort inside your own code, and how to handle the error that results.
What this chapter assumes
You should already know the following:
Promise<T>, async functions, andawait.try/catchwith anunknowncatch variable, from the error-handling chapter.- How to build a promise with
new Promise, from the chapter on wrapping callbacks. - Basic type narrowing.
The examples use a recent TypeScript (5.x) with "lib": ["ES2022", "DOM"]. You can also use Node's type definitions, since Node 18 and later provide fetch and AbortController globally.
Why promises cannot be cancelled
Suppose a user types a search term, then changes it before the first request returns. The first response is now stale. Awaiting a promise does not stop the work behind it. The request keeps running, uses bandwidth, and may overwrite newer results when it finishes.
The solution is cooperative. The caller creates a controller and passes the controller's signal to the work. Later, the caller asks the controller to abort. The work watches the signal and stops itself.
AbortControlleris the object that holds the power to cancel. It has anabort(reason?)method and asignalproperty.AbortSignalis the read-only side. It hasaborted: boolean,reason: any, and anabortevent. It also has athrowIfAborted()method.
Splitting the two objects lets you hand a signal to code that may observe cancellation but cannot trigger it.
Accepting a signal in your own function
The convention is an optional trailing parameter of type AbortSignal. Functions that take options usually put it in an options object as signal, as fetch does. This function comes from the topic's examples:
async function fetchJson<T>(url: string, signal?: AbortSignal): Promise<T> {
const res = await fetch(url, { signal });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return (await res.json()) as T;
}Three typing points matter here:
- The parameter is optional, so existing callers keep working. Passing
undefinedtofetchis the same as passing no signal. - The return type is still
Promise<T>. An aborted call does not return a special value. It rejects, so the abort is an error path and not part ofT. - The
as Ton the last line is an assertion, not a check. The compiler trusts it. The chapter on validating data at async boundaries replaces it with real validation.
Using the function looks like this:
const controller = new AbortController();
const pending = fetchJson<string[]>("https://example.com/api/items", controller.signal);
controller.abort();
pending.catch((err: unknown) => {
console.log("stopped:", err);
});Because abort() runs before the response arrives, pending rejects. Always attach a handler, as the catch call does here. Otherwise the rejection is a floating promise and surfaces as an unhandled rejection.
The abort reason is untyped
signal.reason has type any. When you call controller.abort() with no argument, the reason is a DOMException whose name is "AbortError". You may pass any value instead, such as a string, an Error, or an object.
Because the rejection value also reaches your catch block as unknown, check it before use. A small type guard keeps this in one place:
function isAbortError(err: unknown): boolean {
return (
typeof err === "object" &&
err !== null &&
"name" in err &&
err.name === "AbortError"
);
}A name check is preferable to instanceof DOMException for two reasons. DOMException does not exist as a global in every older runtime. A custom reason passed to abort() also won't be a DOMException.
Typical pattern: replace the previous request
Search-as-you-type needs only the newest result. Each new search aborts the previous one:
let current: AbortController | undefined;
async function search(query: string): Promise<string[] | undefined> {
current?.abort();
const controller = new AbortController();
current = controller;
try {
const url = `https://example.com/api/search?q=${encodeURIComponent(query)}`;
return await fetchJson<string[]>(url, controller.signal);
} catch (err) {
if (isAbortError(err)) {
return undefined;
}
throw err;
}
}The return type is Promise<string[] | undefined>. The undefined is a deliberate part of the contract: it means "superseded, nothing to show". The compiler then forces callers to handle that case before they use the array. This is the one place where the type system carries cancellation information, and you choose to model it that way.
An AbortController is single use. After abort(), its signal stays aborted forever, so create a new controller for each operation.
Reacting to a signal in your own code
Passing the signal to fetch works because fetch already listens to it. For your own work, you must listen yourself. There are three ways to observe a signal:
| Tool | When to use it | Behavior |
|---|---|---|
| `signal.aborted` | Check at a convenient point in a loop | Returns a boolean and never throws |
| `signal.throwIfAborted()` | Same, but you want to stop | Throws `signal.reason` if aborted |
| `signal.addEventListener("abort", ...)` | Wait on something that blocks, such as a timer | Calls your handler once when the abort happens |
A cancellable delay combines the check and the event. It is the signal-aware version of the delay from the chapter on creating promises:
function delay(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise<void>((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => {
clearTimeout(timer);
reject(signal?.reason);
};
const timer = setTimeout(() => {
signal?.removeEventListener("abort", onAbort);
resolve();
}, ms);
signal?.addEventListener("abort", onAbort, { once: true });
});
}The details that make this correct:
- It checks
signal.abortedfirst, because a signal that is already aborted never fires anotherabortevent. Without this check the promise would wait the full delay. - It clears the timer on abort so that nothing keeps running.
- It removes the listener when the timer finishes. A long-lived signal that is reused across many delays would otherwise collect dead listeners.
- It rejects with
signal.reason, not with a new error. Callers can then distinguish reasons uniformly.
The same idea applies in a loop that does chunked work. Call signal.throwIfAborted() at the top of each iteration:
async function processAll(items: string[], signal: AbortSignal): Promise<number> {
let done = 0;
for (const item of items) {
signal.throwIfAborted();
await delay(10, signal);
console.log("processed", item);
done++;
}
return done;
}Abort-aware retry
A retry helper must not retry a cancelled operation. It should also stop waiting between attempts when the signal fires. This combines the earlier pieces, with the generic parameter T preserving the resolved type:
async function retry<T>(
task: (signal: AbortSignal) => Promise<T>,
attempts: number,
signal: AbortSignal,
): Promise<T> {
let lastError: unknown;
for (let i = 0; i < attempts; i++) {
signal.throwIfAborted();
try {
return await task(signal);
} catch (err) {
if (signal.aborted || isAbortError(err)) {
throw err;
}
lastError = err;
await delay(100 * 2 ** i, signal);
}
}
throw lastError;
}Testing signal.aborted first covers custom abort reasons that isAbortError would miss. After the loop, lastError is unknown. Throwing an unknown value is allowed by the compiler, but a caller then catches unknown again, as in the error-handling chapter.
Timeouts and combining signals
Two static helpers cover most time-based cancellation:
AbortSignal.timeout(ms)returns a signal that aborts itself aftermsmilliseconds. Its reason is aDOMExceptionnamed"TimeoutError", so you can tell a timeout from a manual abort.AbortSignal.any(signals)returns a signal that aborts when any input signal aborts, using that signal's reason.
Together they let you honor both a caller's cancel and your own deadline:
async function loadWithDeadline(
url: string,
userSignal: AbortSignal,
): Promise<unknown> {
const signal = AbortSignal.any([userSignal, AbortSignal.timeout(5000)]);
try {
return await fetchJson<unknown>(url, signal);
} catch (err) {
const timedOut =
signal.aborted &&
typeof signal.reason === "object" &&
signal.reason !== null &&
signal.reason.name === "TimeoutError";
if (timedOut) {
throw new Error(`Request to ${url} timed out after 5 seconds`);
}
throw err;
}
}The signal.reason.name access compiles because reason is any. The typeof and null checks protect against a custom reason with no name.
What a signal cannot do
Cancellation is a request, and the code on the other end can ignore it. Keep these limits in mind:
- A function that accepts a signal but never reads it is cancellable only by its signature. The type
AbortSignalis no proof that the function honors it. - Aborting does not undo side effects. A
POSTthat the server has already processed stays processed, even though the client sees a rejection. Promise.raceandPromise.anydo not cancel the losers. If you race two requests, abort the other one yourself after the first settles. The usual way is to give both requests one shared controller and callabort()on it in afinallyblock.- Async generators from the next chapter can also take a signal. The
for awaitloop is cancelled by breaking out of it, which calls the generator'sreturn, or by passing the signal into the generator.
Summary of the typing rules
| Situation | Typing choice | Column |
|---|---|---|
| Optional cancellation | `signal?: AbortSignal` as the last parameter | |
| Required cancellation | `signal: AbortSignal`, as in `retry` above | |
| Result of an aborted call | Reject, so `T` is unchanged | |
| Cancel is a normal outcome | Return `T \ | undefined`, so callers must handle it |
| Catch variable | `unknown`, narrowed with a guard and `signal.aborted` | |
| Abort reason | `any`, so narrow before use |
Exercise
A function getData(url: string, signal: AbortSignal): Promise<string> is called with a signal that was already aborted before the call started. It does const res = await fetch(url, { signal }). Does fetch start a request, and what does the returned promise do? Then say what an onAbort listener registered after that point would do, and why delay checks signal.aborted first.
Show answer
fetch does not send a request. It returns a promise that rejects right away with signal.reason, an AbortError DOMException unless a custom reason was given. A listener added after the signal is already aborted never runs, because the abort event fires only once, at the moment of aborting. delay therefore checks signal.aborted before registering a listener. Without that check, a call with an already-aborted signal would wait the whole timeout and then resolve instead of rejecting.
Exercise
Write the signature and body of fetchFirst(urls: string[]): Promise<string>. It should request every URL as text and resolve with the first response to finish. It should abort all of the other requests once one has finished. Which Promise combinator fits, and where does the abort call go?
Show answer
Use Promise.any for the first fulfilled response, with one shared controller. The abort goes in a finally block, so it also runs on failure.
async function fetchFirst(urls: string[]): Promise<string> {
const controller = new AbortController();
try {
return await Promise.any(
urls.map(async (url) => {
const res = await fetch(url, { signal: controller.signal });
return res.text();
}),
);
} finally {
controller.abort();
}
}
The result type is Promise<string>. If every request fails, Promise.any rejects with an AggregateError. Promise.race would also pick the first to finish, but it settles on the first rejection too.