Skip to content
jshacks.dev
Async

Cancellation in JavaScript: AbortController and AbortSignal

A complete guide to cancelling work in JavaScript with AbortController and AbortSignal on Node.js 24: fetch, timers, streams, servers, UIs and your own code.

28 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, RabbitMQ, Node.js, Redis and Apache Kafka logos.

Starting an asynchronous operation is easy. Stopping one is the part nobody plans for. A user types a new search before the last one returned. A page navigates away while a download is running. A request has a deadline and the dependency is slow. A server's client disconnects while the database is still crunching its query. A shutdown begins with hundreds of jobs in flight. In each case, the result of the work is no longer wanted, and the work, if left alone, keeps consuming sockets, memory, processor time and money, and sometimes writes its stale result over a newer one. JavaScript promises have no way to stop what they represent, because a promise is only a record of an outcome and has no control over the operation that produces it. The platform's answer is a pair of objects, AbortController and AbortSignal, and a convention: an operation that can be stopped accepts a signal, listens to it and cleans up when it fires. This guide covers cancellation from end to end on Node.js 24 and in current browsers: what the objects are, how fetch, timers, files, streams and child processes use them, how to write your own cancellable functions without leaking, how to compose deadlines and several cancellation sources, how to use them in user interfaces and servers and how to test the result. Every example prints the output it produces.

The guide is long because cancellation touches every layer of an application, and the mistakes are specific to each. You can read it through, or use the headings to find the part you need. The shorter posts on AbortController and on timeouts and combined signals cover the two APIs on their own, and this guide builds the whole practice around them.

Why promises cannot be cancelled

A promise is a record of the eventual result of an operation, not a handle on the operation. When you hold a promise for a download, you hold a place where the outcome will appear. The download itself belongs to the code that started it, and nothing in the promise lets you reach it. The language designers considered adding cancellation to promises, and the idea was withdrawn, for good reasons: a promise can have many consumers, and one of them cancelling would change the outcome for the rest, and a cancelled state would be a fourth outcome that every handler would need to deal with.

The consequence is that "cancelling" a promise can only mean one of two things. Either you stop caring about the result, which frees you from waiting and leaves the work running, or you tell the underlying operation to stop, which needs a channel that the operation listens to. The first is cheap and incomplete. The second is cancellation proper, and the channel is the AbortSignal.

JavaScript
const delay = (ms, value) =>
  new Promise((resolve) => setTimeout(() => resolve(value), ms));

let sideEffects = 0;

async function work() {
  await delay(30);
  sideEffects += 1; // the operation's real effect
  return "finished";
}

const result = await Promise.race([work(), delay(5, "gave up waiting")]);

console.log(result);

await delay(50);
console.log("work still ran to completion:", sideEffects === 1);
Text
gave up waiting
work still ran to completion: true

The race returned after five milliseconds, and the loser carried on and produced its side effect anyway. For a pure computation that is a waste. For an operation that writes to a database or sends an email, it is a correctness problem, and it is the reason that giving up on a result and stopping the work are different things that need different tools.

The two objects

An AbortController creates a signal and can fire it. An AbortSignal is a read-only object that reports whether cancellation has been requested, fires an abort event when it is and carries the reason. Splitting them is the design: the code that starts an operation holds the controller, and the code that runs the operation receives only the signal, so it can observe cancellation without being able to trigger it.

JavaScript
const controller = new AbortController();
const { signal } = controller;

console.log("aborted before:", signal.aborted);

signal.addEventListener("abort", () => {
  console.log("abort event fired");
});

controller.abort();

console.log("aborted after:", signal.aborted);
console.log("reason:", signal.reason.name, signal.reason.message);
Text
aborted before: false
abort event fired
aborted after: true
reason: AbortError This operation was aborted

The message text comes from the platform's default DOMException and may differ slightly between runtimes, so branch on the name, not the message. Three properties of the objects are worth fixing in mind.

A signal is single use. Once aborted, it stays aborted forever, abort() called again does nothing and there is no way to reset it. To cancel a second operation, create a second controller.

A signal is synchronous. Calling abort() flips signal.aborted and runs the listeners before it returns. The operations that listen react in their own time, but the state is changed at once.

A signal carries a reason. abort(reason) lets you pass any value, and signal.reason returns it. With no argument, the reason is an AbortError. Pass an Error with a message that says why, so that logs say "user navigated away" and not "aborted".

JavaScript
const controller = new AbortController();

controller.abort(new Error("user navigated away"));

console.log(controller.signal.reason.message);
Text
user navigated away

Two static helpers create signals without a controller. AbortSignal.abort(reason) returns a signal that is already aborted, which is handy for tests and for passing a cancelled state through an API. AbortSignal.timeout(ms) returns a signal that aborts itself after a delay, with a TimeoutError reason. The timeout section below covers it, along with AbortSignal.any.

Cancelling fetch

fetch accepts a signal option. When the signal aborts, the request is cancelled, the connection is released and the promise rejects with the signal's reason. If the response has already arrived, an abort still cancels reading the body, so response.text() rejects.

JavaScript
const controller = new AbortController();

const request = fetch("https://example.com/slow", { signal: controller.signal });

setTimeout(() => controller.abort(new Error("changed my mind")), 10);

try {
  await request;
} catch (error) {
  console.log(error.message);
}
Text
changed my mind

The rejection carries the reason you supplied. When you pass your own Error, fetch rejects with that exact object, so error.name is Error, and when you pass nothing, it rejects with an AbortError. The consequence is that a catch that tests error.name === "AbortError" misses aborts that carry a custom reason. A reliable approach is to test the signal, not the error: if (signal.aborted) { /* we cancelled it */ }.

JavaScript
async function load(url, signal) {
  try {
    const response = await fetch(url, { signal });
    return await response.text();
  } catch (error) {
    if (signal.aborted) return null; // we asked for this
    throw error;
  }
}

Aborting a fetch closes the connection, and the server may already have started handling the request. For a read, no harm done. For a write, such as POST /orders, the server may have created the order while the client believes the request was cancelled. Abort means "I stopped waiting", and it does not mean "it did not happen". Writes need idempotency keys, so a retry after an abort does not duplicate the effect, and a request you might abort should be one that is safe to abandon.

Cancelling the platform's own APIs

A growing list of APIs accept a signal. In Node.js, the promise APIs for timers, files, streams, child processes and events do.

JavaScript
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);
}
Text
AbortError ABORT_ERR

The sleep ended after about ten milliseconds, and its timer was cleared, so the process does not wait for a second it no longer needs. Node.js errors from aborts carry code set to ABORT_ERR, and the name is AbortError.

The same option appears on fs.promises.readFile and writeFile, which can abort between chunks, on events.once and events.on, which stop waiting for an event, on child_process.exec and spawn, which kill the child process when the signal fires, on readline, on stream.pipeline, on http requests through the signal option, and on AbortSignal.timeout handling in fetch. In browsers, addEventListener accepts a signal too, which removes the listener when the signal aborts, one of the neatest uses of the API.

JavaScript
const controller = new AbortController();

const target = new EventTarget();
let calls = 0;

target.addEventListener("ping", () => calls++, { signal: controller.signal });

target.dispatchEvent(new Event("ping"));
controller.abort();
target.dispatchEvent(new Event("ping"));

console.log("calls:", calls);
Text
calls: 1

One signal can remove any number of listeners, which replaces the bookkeeping of keeping a reference to every handler so that you can pass it to removeEventListener. In a component that registers a dozen listeners, a single controller.abort() on teardown removes them all.

Child processes show what real cancellation means: the signal ends the process, which is an actual stop, not just a stop of waiting.

JavaScript
import { spawn } from "node:child_process";

const controller = new AbortController();

const child = spawn("sleep", ["30"], { signal: controller.signal });

child.on("error", (error) => console.log(error.name));

setTimeout(() => controller.abort(), 20);

await new Promise((resolve) => child.on("close", resolve));
console.log("child ended:", child.killed);
Text
AbortError
child ended: true

This assumes a Unix-like system with a sleep command. The child received a SIGTERM, and the error event reported the abort. Cancellation reaching down to a real process is the most complete form of stopping work.

Writing your own cancellable function

An API that takes a signal is only useful if it does something with it. When you write a function that does asynchronous work, the pattern has four parts: refuse to start if the signal is already aborted, listen for the abort event, release whatever the function holds when it fires and make the promise reject with signal.reason. Do not forget to stop listening when the work finishes normally.

JavaScript
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 the caller"));

try {
  await pending;
} catch (error) {
  console.log(error.message);
}

console.log(await waitFor(5));
Text
cancelled by the caller
done

Each part matters. The early check handles a signal that was aborted before the call, since the event never fires again for a listener added after the fact. The clearTimeout in onAbort releases the resource, and without it the timer would keep the process alive. The removeEventListener on success stops a long-lived signal from holding a reference to a finished operation, which becomes a leak when one signal is shared by thousands of short operations. And the rejection with signal.reason lets callers see why.

For functions that do their work in steps with await, you do not need a listener. Check the signal between steps. signal.throwIfAborted() throws the reason if the signal is aborted, which makes the check one line.

JavaScript
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, 6], { signal: controller.signal });
} catch (error) {
  console.log("stopped:", error.message);
}
Text
stopped: stop

Cancellation takes effect at the next check, so its granularity is as fine as your checks. A function that does one long synchronous step cannot be cancelled in the middle of it, since nothing runs while it holds the thread, and not even the abort event can be delivered. For heavy work, check the signal in the loop, or run the work in a worker and terminate the worker.

Pass the signal down. If your function calls other functions that accept a signal, give them yours, so that one abort reaches the whole operation. A signal that is accepted and never forwarded is a common reason that cancellation "works" at the top and the real work continues underneath.

JavaScript
async function loadDashboard({ signal }) {
  const [user, stats] = await Promise.all([
    fetch("data:application/json,{\"name\":\"Ada\"}", { signal }).then((r) => r.json()),
    fetch("data:application/json,{\"visits\":3}", { signal }).then((r) => r.json()),
  ]);

  return `${user.name} has ${stats.visits} visits`;
}

console.log(await loadDashboard({ signal: new AbortController().signal }));
Text
Ada has 3 visits

Cleanup belongs in finally

Cancellation is an early exit, and early exits skip the code after them. Anything the function acquired, a file handle, a lock, a spinner, a timer, must be released on every path, which is what try/finally is for.

JavaScript
async function withLock(lock, work, { signal }) {
  await lock.acquire({ signal });

  try {
    signal.throwIfAborted();
    return await work();
  } finally {
    lock.release();
  }
}

The same applies to async generators. When a for await loop exits early, the runtime calls the generator's return(), which resumes it as if a return statement stood at the yield, so its finally blocks run. A generator that holds a resource should put its release there, and consumers can then stop with a plain break.

JavaScript
async function* readPages(signal) {
  try {
    for (let page = 1; page <= 5; page++) {
      signal.throwIfAborted();
      await new Promise((resolve) => setTimeout(resolve, 5));
      yield page;
    }
  } finally {
    console.log("generator cleanup ran");
  }
}

const controller = new AbortController();

try {
  for await (const page of readPages(controller.signal)) {
    console.log("page", page);
    if (page === 2) controller.abort();
  }
} catch (error) {
  console.log("loop ended with:", error.name);
}
Text
page 1
page 2
generator cleanup ran
loop ended with: AbortError

After the abort, the loop asked for page three, the generator checked the signal and threw, and the finally ran before the error reached the consumer. A real consumer decides whether an abort is an error or a normal exit, and the catch here is where that decision goes.

Timeouts, and combining signals

A deadline is a cancellation that fires on a timer, and AbortSignal.timeout(ms) packages it: a signal that aborts itself after the delay with a TimeoutError. It replaces the pattern of a manual timer, a controller and a listener, and it has two helpful properties. There is nothing to clean up, since the signal owns its timer, and the timer does not keep a Node.js process alive. The reason is a TimeoutError, which lets callers tell "we gave up waiting" from "the user cancelled".

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

try {
  await sleep(1000, null, { signal: AbortSignal.timeout(15) });
} catch (error) {
  console.log(error.name);
}
Text
TimeoutError

The countdown starts when you call AbortSignal.timeout, not when the operation starts, so create it right before use. A signal created at module load and used minutes later is already aborted.

AbortSignal.any(signals) returns a signal that aborts as soon as any of the inputs does, with that input's reason. It is how you say "cancel when the user presses stop, or when the page unloads, or after five seconds".

JavaScript
const user = new AbortController();
const shutdown = new AbortController();

const combined = AbortSignal.any([user.signal, shutdown.signal, AbortSignal.timeout(1000)]);

combined.addEventListener("abort", () => {
  console.log("aborted because:", combined.reason.message);
});

shutdown.abort(new Error("server is shutting down"));
Text
aborted because: server is shutting down

A function that takes a caller's signal and wants to add its own deadline composes the two without taking over the caller's control.

JavaScript
function request(url, { signal, timeoutMs = 5000 } = {}) {
  const signals = [AbortSignal.timeout(timeoutMs)];
  if (signal) signals.push(signal);

  return fetch(url, { signal: AbortSignal.any(signals) });
}

When the function is called with the caller's signal, either source can end the request. Create combined signals per operation, since a combined signal registers itself with its sources, and thousands of them built from one long-lived signal pile up until they are collected. AbortSignal.timeout arrived in Node.js 17.3 and AbortSignal.any in Node.js 20.3, and both are in current browsers.

A last note on deadlines: they add up. Three sequential calls with five-second timeouts can take fifteen. When the caller cares about the total, create one signal at the start of the operation and pass it to every step, so the limit applies to the whole.

Cancelling streams and pipelines

Streams move data in chunks, and a pipeline that is no longer wanted should stop reading its source and release its destination. Node.js's stream.pipeline accepts a signal in its options, and aborting it destroys all the streams in the chain and rejects with an AbortError.

JavaScript
import { Readable, Writable } from "node:stream";
import { pipeline } from "node:stream/promises";

const controller = new AbortController();

const slowSource = Readable.from(
  (async function* () {
    for (let i = 1; i <= 100; i++) {
      await new Promise((resolve) => setTimeout(resolve, 5));
      yield `chunk ${i}`;
    }
  })(),
);

let received = 0;
const sink = new Writable({
  write(chunk, encoding, callback) {
    received += 1;
    callback();
  },
});

setTimeout(() => controller.abort(), 28);

try {
  await pipeline(slowSource, sink, { signal: controller.signal });
} catch (error) {
  console.log(error.name, "after fewer than 100 chunks:", received < 100);
}
Text
AbortError after fewer than 100 chunks: true

Web Streams offer the same through pipeTo(destination, { signal }) and pipeThrough(transform, { signal }), and a ReadableStream's cancel(reason) method tells the source to stop producing. Aborting a pipeline also gives the source a chance to clean up, so a file read stream closes its descriptor. The posts on streams and backpressure cover the rest.

Cancelling work in a worker

Signals do not cross thread boundaries, since a signal is an object in one realm, and a worker lives in another. The tools for stopping a worker are therefore different. worker.terminate() stops it immediately and abruptly, without running its cleanup code. For a graceful stop, send a message, and let the worker check for it between steps, or share an Int32Array over a SharedArrayBuffer as a cancellation flag that the worker reads with Atomics.load.

JavaScript
import { Worker, isMainThread, workerData } from "node:worker_threads";

if (isMainThread) {
  const flag = new Int32Array(new SharedArrayBuffer(4));
  const worker = new Worker(new URL(import.meta.url), { workerData: flag });

  setTimeout(() => Atomics.store(flag, 0, 1), 20); // request cancellation

  await new Promise((resolve) => worker.on("exit", resolve));
  console.log("worker stopped itself cleanly");
} else {
  while (Atomics.load(workerData, 0) === 0) {
    // long-running work, checked once per iteration
  }
}
Text
worker stopped itself cleanly

Whether to use terminate() or a flag depends on what the worker holds. If it only computes, terminate it. If it has files open or half-written output, ask it to stop and let it finish its cleanup. The post on shared memory explains the primitives used here.

Cancellation in user interfaces

Interfaces are full of work whose result is wanted only while some condition holds, and the same pattern applies everywhere: create a controller when the work starts, abort it when the condition ends, and treat an abort as an expected outcome.

Search as you type. Each keystroke starts a request, and the previous request is obsolete the moment the next one starts. Abort the previous controller before creating the next, so that a stale response can never overwrite a newer one.

JavaScript
let current;

async function search(query) {
  current?.abort();
  current = new AbortController();
  const { signal } = current;

  try {
    await waitFor(20, { signal }); // stands in for fetch(url, { signal })
    return `results for ${query}`;
  } catch (error) {
    if (signal.aborted) return null; // superseded by a newer search
    throw error;
  }
}

const first = search("ja");
const second = search("jav");

console.log(await first, await second);
Text
null results for jav

This assumes the waitFor helper from the earlier section. The first search was cancelled by the second, resolved with null and never reported stale results. Treating the abort as a normal result keeps it out of error logs. This is the cancellation form of the race described in the post on race conditions, and it is better than a sequence number alone, since it stops the stale work and not only its result.

Component lifecycles. A component that starts a request when it mounts should abort it when it unmounts, since the response would update a component that no longer exists. In React, the cleanup function returned from an effect is where the abort goes.

JSX
useEffect(() => {
  const controller = new AbortController();

  fetch(`/api/items/${id}`, { signal: controller.signal })
    .then((response) => response.json())
    .then(setItem)
    .catch((error) => {
      if (!controller.signal.aborted) setError(error);
    });

  return () => controller.abort();
}, [id]);

When id changes, React runs the cleanup of the old effect, which aborts the old request, before running the new one. The catch ignores the abort. Other frameworks have the same hook points: a destroy callback in Vue and Angular, an onDestroy in Svelte.

Navigation. In a single-page application, leaving a route should abort the requests that route started. The same controller can serve a whole page's worth of work, and one abort() ends it all.

Buttons. A cancel button holds the controller of the operation it controls. Disable the button when the operation finishes, and create a fresh controller for the next run.

Cancellation on the server

On a server, the question is what to cancel when the client goes away, and the answer is nearly always the work done on the client's behalf. Node.js exposes the connection's state, and a common approach turns the close event of the response or request into an abort.

JavaScript
import { createServer } from "node:http";

const server = createServer(async (request, response) => {
  const controller = new AbortController();
  response.on("close", () => {
    if (!response.writableFinished) controller.abort(new Error("client disconnected"));
  });

  try {
    const result = await slowQuery({ signal: controller.signal });
    response.end(result);
  } catch (error) {
    if (controller.signal.aborted) return; // nobody is listening any more
    response.statusCode = 500;
    response.end("error");
  }
});

Here slowQuery stands for any function that accepts a signal and stops its work when it fires, such as a database client with cancellation support. A query abandoned by a client that has gone, and left to finish, wastes a connection from the pool for as long as it runs, and under load that waste becomes an outage. Frameworks increasingly provide a request-scoped signal that does this wiring for you, and it is worth using where available.

Server shutdown is the other major source. A process that receives SIGTERM should stop accepting new work, signal in-flight work to wrap up and wait for it to finish within a limit. A shared AbortController whose signal is combined into every operation's signal, with AbortSignal.any, makes that practical.

JavaScript
const shutdown = new AbortController();

process.once("SIGTERM", () => shutdown.abort(new Error("shutting down")));

function operationSignal(requestSignal) {
  return AbortSignal.any([requestSignal, shutdown.signal, AbortSignal.timeout(30_000)]);
}

Each operation now stops on the first of three causes: its own request being cancelled, the process shutting down and a thirty-second deadline.

Retries and cancellation together

A retry loop must honor cancellation in two places: before each attempt, and during the wait between attempts. A loop that sleeps through a backoff without watching the signal makes a cancelled operation keep waiting.

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

async function retry(operation, { attempts = 4, baseMs = 20, signal } = {}) {
  let lastError;

  for (let attempt = 1; attempt <= attempts; attempt++) {
    signal?.throwIfAborted();

    try {
      return await operation(attempt, signal);
    } catch (error) {
      if (signal?.aborted) throw signal.reason;
      lastError = error;
      if (attempt < attempts) await sleep(baseMs * 2 ** (attempt - 1), null, { signal });
    }
  }

  throw new Error(`failed after ${attempts} attempts`, { cause: lastError });
}

const controller = new AbortController();
setTimeout(() => controller.abort(new Error("caller gave up")), 30);

try {
  await retry(async () => {
    throw new Error("still failing");
  }, { signal: controller.signal });
} catch (error) {
  console.log(error.message);
}
Text
caller gave up

The cancellation stopped the loop during a backoff wait, because the sleep also received the signal, and the loop did not run its remaining attempts. Each attempt received the signal too, so an in-flight call could stop. Notice that an aborted attempt is not counted as a failure to retry, since the code checks the signal before recording the error.

Testing cancellation

Cancellation has three behaviors to test: it works when requested in the middle, it works when requested before the start and it releases what the function held. Write a test for each, using a controller you control and fake or tiny delays.

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("rejects with the reason when aborted in the middle", async () => {
  const controller = new AbortController();
  const pending = waitFor(1000, { signal: controller.signal });

  controller.abort(new Error("stop"));

  await assert.rejects(pending, { message: "stop" });
});

test("does not start when the signal is already aborted", async () => {
  const signal = AbortSignal.abort(new Error("already"));

  await assert.rejects(waitFor(1000, { signal }), { message: "already" });
});
Text
āœ” rejects with the reason when aborted in the middle
āœ” does not start when the signal is already aborted

To test cleanup, make the dependency observable, such as a fake resource that records acquire and release calls, abort in the middle and assert that every acquire has a matching release. A hung test runner at the end of the suite is the classic symptom of a timer or listener that cancellation failed to clear, so treat it as a failed test of cleanup. For deadlines, avoid waiting in real time. Use a controller and abort it by hand with a TimeoutError reason, or use fake timers where the runner supports them.

Pitfalls and how to avoid them

Accepting a signal and ignoring it. The function advertises cancellation and cannot deliver it. Every function that takes a signal must check it, listen to it or forward it.

Forgetting to forward. The top-level function listens, and the calls underneath do not receive the signal, so work continues below. Pass it down every layer.

Leaving listeners behind. Adding an abort listener to a long-lived signal without removing it on success leaks one closure per operation. Use { once: true } and remove the listener when the work finishes.

Reusing a controller. A signal stays aborted, so a controller shared across operations cancels every later operation immediately. Create one per operation or group of operations.

Treating an abort as an error. Logging every cancelled search as a failure fills the logs with noise and hides real problems. Check signal.aborted and treat it as an expected outcome.

Matching on the error name only. A custom reason has no AbortError name, so test the signal and not the error.

Assuming abort undoes the work. It stops waiting and, at best, stops the remaining work. Effects that already happened remain, and writes need idempotency.

Storing one controller in module scope. Unrelated operations then cancel each other. Create controllers close to where they are used, and name them for what they cancel.

Starting the timeout too early. AbortSignal.timeout counts from creation. Create it at the point of use.

Blocking the thread. A long synchronous step cannot be interrupted, because nothing, including the abort event, runs while it holds the thread. Check the signal inside loops, or move the work to a worker.

How other designs compare

Other languages and libraries have their own answers, and comparing them clarifies the choices in the platform's. Go passes a context.Context down every call, which carries a cancellation signal, a deadline and request-scoped values together, and the convention that the first parameter of a function is the context is strict. .NET passes a CancellationToken, which is a read-only token created by a CancellationTokenSource, the same split as signal and controller. Rust's async functions cancel by being dropped, which is automatic and requires care about what drops in the middle. RxJS gives subscriptions an unsubscribe method that runs the producer's teardown, which is cancellation built into the type.

JavaScript's design sits closest to .NET's. It is explicit and cooperative, with no automatic cancellation, and it composes by passing the signal along. The cost is that every function in the chain must take part. The benefit is that cancellation works across libraries, runtimes and the platform, with one convention, and that the tools for it, AbortSignal.timeout, AbortSignal.any, throwIfAborted and addEventListener's signal option, are standard and available in browsers, Node.js, Deno and Bun alike.

Within JavaScript, observables take a different route. An RxJS subscription cancels by unsubscribe(), and operators such as switchMap cancel the previous inner work for you, as described in the post on switchMap. If your application is built around observables, use them. If it is built around promises and async/await, which most are, use signals.

A checklist for any cancellable operation

When you add cancellation to an operation, or review one, walk through a short list. Does the function accept a signal in its options? Does it check signal.aborted, or call throwIfAborted(), before it starts, and between steps? Does it listen for the abort event if it waits on something that does not check? Does it pass the signal to every function it calls that accepts one? Does it release every resource it holds in a finally, or in the abort handler? Does it reject with signal.reason, so that callers can see why? Does it remove its listeners on success? Do callers treat the abort as an expected outcome? And is there a deadline, so that a call that never answers eventually ends?

An operation that passes that list can be stopped when the user changes their mind, when the page is closed, when the client disconnects, when the deadline passes and when the process shuts down. That is what cancellation from end to end means, and the platform's signals are enough to build it.

Designing the API of a cancellable function

When you write functions that others will call, where the signal goes is a design decision, and a few conventions keep it predictable. Put the signal in an options object under the name signal, as the platform does, and not in a positional argument. A call such as load(id, { signal }) reads clearly, leaves room for other options and matches what every caller already knows from fetch. Make the signal optional, so that callers who do not care about cancellation are not forced to create a controller, and handle its absence with optional chaining, as the examples do.

Decide what the function promises on abort. The convention, followed by the platform, is that the returned promise rejects with signal.reason, so a caller can learn why. Some libraries resolve with a special value instead, which makes the abort path look like success and invites bugs, so prefer the rejection. Document that callers should expect it, and tell them how to recognize it. If your library has its own error hierarchy, you can wrap the reason in a CancelledError with the original as its cause, as long as the wrapper is documented and consistent.

Be clear about what happens to partial work. A function that writes ten records and is aborted after four should say whether the four remain, are rolled back or are reported to the caller. For operations where partial effects are dangerous, such as a multi-step update, do the abort check before the first write and after the last, and make the steps in between uninterruptible, or run them inside a transaction that the abort rolls back. Cancellation that leaves data half-written is worse than no cancellation.

Finally, think about the granularity of checks. A check before each network call is natural. A check inside a tight loop costs a property read per iteration, which is cheap, and gives much finer control. A check only at the start of a long function is little better than none. Aim for a check at every point where stopping would be safe and where the function might otherwise run for a noticeable time.

Reasons that explain themselves

The reason you pass to abort() shows up in logs, in error reports and in the code that handles the rejection, so it is worth a little design. A bare abort() produces an AbortError with a generic message, which tells nobody why. Passing an Error with a specific message costs nothing and makes every downstream log line informative: "user navigated away", "request superseded by a newer search", "server shutting down".

When different causes need different handling, give the reasons a type. A deadline is a TimeoutError, which AbortSignal.timeout already provides. A shutdown might deserve its own class or a code property, so that handlers can decide whether to retry. A user cancellation should not be retried, a timeout may be, and a shutdown must not start new work.

JavaScript
class ShutdownError extends Error {
  name = "ShutdownError";
}

const controller = new AbortController();
controller.abort(new ShutdownError("server is shutting down"));

const reason = controller.signal.reason;

console.log(reason.name, reason instanceof ShutdownError);
console.log(reason.message);
Text
ShutdownError true
server is shutting down

Callers can now branch with instanceof, or on name, to choose between retrying, giving up quietly and reporting. This is a better design than parsing messages, and it works across the combined signals from AbortSignal.any, which preserve the reason of whichever source fired first.

Seeing cancellation in production

Cancellation that nobody observes is cancellation nobody can tune. Record cancelled operations as their own category and not as errors, with the reason and how far they had progressed. A rise in cancelled searches is normal during busy typing. A rise in cancelled requests with the reason "client disconnected" may mean that responses are too slow and users are giving up. A rise in timeouts points at a dependency. Each tells you something different, and lumping them with failures hides all of it.

Two metrics are especially useful. The first is the fraction of operations that end in cancellation, by reason. The second is the time between the abort and the moment the work actually stopped. Cancellation is cooperative, and an operation that notices the signal five seconds late is not much of a cancellation. If the second number is large, find the step that does not check the signal, which is nearly always a long synchronous step or a call that was not given the signal.

In a server, a cancelled operation should also release what it holds, and a metric that tracks open connections, held locks or in-flight queries confirms that the release happens. After a burst of cancellations, those numbers should return to their baseline within moments. If they do not, something is leaking on the abort path, and that path is the one least likely to have been tested.

Cancellation in the browser beyond fetch

Browsers have a few extra places where cancellation matters. When a page is being unloaded, in-flight fetch requests are cancelled by the browser, and a request that must survive, such as an analytics beacon, should use navigator.sendBeacon or fetch with the keepalive option, which lets it outlive the page. Aborting such a request is allowed, but the point of the option is that you usually do not.

Pages restored from the back-forward cache are frozen and thawed, and timers and requests from before the freeze may have been suspended, so logic that depends on a deadline should compare against a clock when it resumes, and not trust that a timer fired. Event listeners registered with a signal are removed when the signal aborts, and that works the same whether the page is live or being torn down, which makes a single page-level controller a convenient way to tidy up everything on unload.

Finally, remember that the signal option of addEventListener is not limited to cleanup at the end of a component's life. You can use a short-lived controller to remove a listener after one event, or after a condition changes, with less code than keeping the handler reference around. Combined with { once: true } for single events, it removes most of the manual bookkeeping that event handling used to need.

Adopting cancellation in an existing code base

Retrofitting cancellation onto code that has none is a common job, and it goes better when done from the outside in. Start at the places where a user or a system can reasonably abandon work: search boxes, route changes, request handlers, long imports and shutdown. Create a controller at each, and pass its signal to the first function called. Then follow the signal inward, adding a { signal } option to each function in turn and forwarding it to whatever that function calls. At the leaves, where the work meets fetch, a file system call or a timer, the platform already accepts the signal, and the chain is complete.

Do this one path at a time, test each and ship it. A half-wired path is harmless, because a function that does not yet accept the option ignores it, and the work behaves as it did before. What you should avoid is pretending that a path is cancellable before the leaves are wired, since the code above would then report a cancellation that the code below never honored.

Where a library gives you no way to pass a signal, wrap it. For a promise-returning call that cannot be stopped, you can still stop waiting by racing it against the signal, and discard the late result. Make the wrapper's behavior explicit in its name and its documentation, since it cancels the waiting and not the work, and the difference matters when the work has side effects.

JavaScript
function abortable(promise, signal) {
  if (signal.aborted) return Promise.reject(signal.reason);

  return new Promise((resolve, reject) => {
    const onAbort = () => reject(signal.reason);
    signal.addEventListener("abort", onAbort, { once: true });

    promise.then(resolve, reject).finally(() => {
      signal.removeEventListener("abort", onAbort);
    });
  });
}

const controller = new AbortController();
const slow = new Promise((resolve) => setTimeout(() => resolve("late result"), 50));

setTimeout(() => controller.abort(new Error("stopped waiting")), 5);

try {
  await abortable(slow, controller.signal);
} catch (error) {
  console.log(error.message);
}
Text
stopped waiting

The wrapper stopped the waiting after five milliseconds, and the slow promise carried on regardless. That is the honest limit of wrapping, and it is why the best fix is always to pass the signal into the real operation when you can. Use the wrapper as a bridge for libraries that have not caught up, and replace it when they do.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.