AbortController Explained
Learn how AbortController and AbortSignal cancel fetch requests, timers and your own async code, with the abort reason, cleanup and the common mistakes.

JavaScript promises cannot be cancelled. Once you start an operation, the promise that represents it has no stop button, and if you stop caring about the result, the work carries on anyway: the request finishes downloading, the timer fires, the query runs. AbortController is the answer the platform settled on. It gives you two linked objects, a controller that you hold and a signal that you hand to the operation. Calling controller.abort() flips the signal into an aborted state and fires an event, and any code that listens to the signal can stop. fetch, node:fs/promises, node:timers/promises, child_process, streams and many libraries accept a signal option, and your own functions can too. This post covers the API on Node.js 24 and current browsers with printed output, shows how to wire a signal into custom code with proper cleanup, explains the abort reason and lists the mistakes that leave work running after an abort.
The two objects
const controller = new AbortController();
const signal = controller.signal;
console.log("aborted before:", signal.aborted);
controller.abort();
console.log("aborted after:", signal.aborted);
console.log("reason:", signal.reason.name);aborted before: false
aborted after: true
reason: AbortErrorThe controller is the part that can abort, and the signal is the read-only view that you pass around. Separating them lets you give an operation the right to observe cancellation without giving it the right to trigger it. abort() can be called once. Later calls do nothing, and the signal stays aborted forever, so a signal is not reusable. Make a new controller for each operation or group of operations.
Listening and the reason
The signal fires an abort event, and its reason property holds why. By default the reason is a DOMException named AbortError, and you can supply your own value.
const controller = new AbortController();
controller.signal.addEventListener("abort", () => {
console.log("abort event, reason:", controller.signal.reason);
});
controller.abort(new Error("user navigated away"));abort event, reason: Error: user navigated away
at ... The stack lines depend on the file, so they are trimmed. Passing an Error is better than relying on the default, because it records the cause. APIs that reject on abort usually reject with signal.reason, so what you pass in is what the caller receives.
Cancelling fetch
fetch rejects with the abort reason when its signal fires, and the connection is torn down.
const controller = new AbortController();
const request = fetch("https://example.com/slow", { signal: controller.signal });
setTimeout(() => controller.abort(), 10);
try {
await request;
} catch (error) {
console.log(error.name);
}AbortErrorThis assumes the request is still in flight after 10 ms, which is true for any real network call. If the response had already arrived, abort() would not affect the promise, though it could cancel reading the body.
Cancelling timers and file operations
Many Node.js promise APIs take signal.
import { setTimeout as sleep } from "node:timers/promises";
const controller = new AbortController();
setTimeout(() => controller.abort(), 10);
try {
await sleep(1000, "finished", { signal: controller.signal });
} catch (error) {
console.log(error.name, error.code);
}AbortError ABORT_ERRThe sleep ended after 10 ms instead of one second, and the timer was cleared. Note the Node.js error has code ABORT_ERR. Check error.name === "AbortError" to treat an abort as an expected outcome and not a failure.
Writing your own cancellable function
The pattern has four parts. Check whether the signal is already aborted. Listen for the abort event. Clean up the listener and the underlying work. Reject with the signal's reason.
function waitFor(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const timer = setTimeout(() => {
signal?.removeEventListener("abort", onAbort);
resolve("done");
}, ms);
function onAbort() {
clearTimeout(timer);
reject(signal.reason);
}
signal?.addEventListener("abort", onAbort, { once: true });
});
}
const controller = new AbortController();
const pending = waitFor(1000, { signal: controller.signal });
controller.abort(new Error("cancelled by caller"));
try {
await pending;
} catch (error) {
console.log(error.message);
}
console.log(await waitFor(5, {}));cancelled by caller
doneThe early aborted check handles a signal that was aborted before the call, since the event would never fire again. The removeEventListener on success stops the signal from holding a reference to a finished operation, which matters when one long-lived signal is shared by many short operations. Node.js and browsers also offer signal.throwIfAborted(), which throws the reason if aborted, convenient at checkpoints in async code.
async function processAll(items, { signal }) {
const done = [];
for (const item of items) {
signal.throwIfAborted();
await new Promise((resolve) => setTimeout(resolve, 5));
done.push(item);
}
return done;
}
const controller = new AbortController();
setTimeout(() => controller.abort(new Error("stop")), 12);
try {
await processAll([1, 2, 3, 4, 5], { signal: controller.signal });
} catch (error) {
console.log("stopped:", error.message);
}stopped: stopThe loop checked the signal before each step, so cancellation took effect at the next boundary. A function that does no checking cannot be cancelled mid-way, and cancellation granularity is as fine as your checks.
Timeouts and combining signals
AbortSignal.timeout(ms) makes a signal that aborts itself, with a TimeoutError reason. AbortSignal.any([a, b]) makes one that aborts when any input does. Both have a dedicated post, AbortSignal.timeout and AbortSignal.any, and the combination is how you write "cancel on user action or after five seconds".
const user = new AbortController();
const combined = AbortSignal.any([user.signal, AbortSignal.timeout(50)]);
try {
await waitFor(1000, { signal: combined });
} catch (error) {
console.log(error.name);
}TimeoutErrorWhat abort does not do
It does not stop code that is not listening. An async function that never checks the signal runs to the end. The caller sees whatever you do with the result.
It does not undo effects. A request aborted halfway may already have been processed by the server. For a write, abort means "I stopped waiting", not "it did not happen".
It does not remove the need for cleanup. Releasing a file handle, closing a connection and clearing a timer all stay your job, in finally.
It does not cancel a promise from outside. Nothing about the promise changes. The cancellation is a cooperative protocol between you and the code that accepts the signal.
A pattern: cancel the previous request
Search boxes and route changes need only the latest result.
let current;
async function search(query) {
current?.abort();
current = new AbortController();
const { signal } = current;
try {
await waitFor(20, { signal });
return `results for ${query}`;
} catch (error) {
if (error.name === "AbortError") return null;
throw error;
}
}
const first = search("ja");
const second = search("jav");
console.log(await first, await second);null results for javThe first call was cancelled by the second, resolved with null and never produced stale results. Treating abort as an expected result keeps it out of error logs.
Where to put the controller
A practical question in application code is who owns the controller. The rule that works is that whoever owns the lifetime owns the controller. A component that starts requests when it mounts creates a controller then, and aborts it when it unmounts. A request handler on a server creates one per request, so a client that disconnects can cancel the downstream work, and a background worker creates one for its whole run and aborts it on shutdown. Pass only the signal further down.
Resist the urge to store a controller in a module-level variable and share it between unrelated operations. One abort then cancels everything, including work that had nothing to do with the original reason, and since a signal can never be reset, the module is stuck with a dead controller until you replace it. Create controllers close to where they are used, name them for what they cancel and let them be garbage collected with the operation they belong to.
A note on libraries and frameworks
Most modern HTTP clients, database drivers and test utilities accept a signal option now, and it is worth checking for it before you build your own cancellation. When you write a library, accept { signal } in your options object, pass it down to every function you call that takes one and check it between steps that do not. Users will then be able to cancel your function the same way they cancel everything else, and combine it with timeouts, without learning anything new. Document the rejection behavior too, saying that the promise rejects with signal.reason, so callers know what to catch.


