Skip to content
jshacks.dev
Async

How to Write Async Code That Is Easy to Cancel

Write async code that is easy to cancel: accept a signal in every function, check it between steps, pass it down, clean up in finally and treat abort as normal.

8 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.

Cancellation is easy to add to one function and hard to add to a system. A search box that cancels its previous request is simple. A data loader that calls five helpers, each of which makes network calls, starts timers and opens streams, is not, unless every one of them was written to be canceled from the beginning. The difference is design, not cleverness. Code that is easy to cancel follows a few rules consistently: every async function takes a signal, passes it on, checks it between steps, cleans up in finally and treats an abort as a normal outcome and not as a failure. This post collects those rules, with code in Node.js 24 and browsers, and shows a worked example where the rules turn a function that cannot be stopped into one that stops within milliseconds. It builds on implementing a cancelable promise and combining AbortSignals.

Rule 1: take a signal, always last, always optional

Give every function that does async work an options object with an optional signal. Make the signal optional so existing callers keep working. Put it last, in the options object, as the platform does with fetch.

rule1.jsJavaScript
export async function loadProfile(userId, { signal } = {}) {
  signal?.throwIfAborted();
  const response = await fetch(`https://api.example.test/users/${userId}`, { signal });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

A signal in the same place in every function means a reader never has to look up how cancellation works for this one. The first line, signal?.throwIfAborted(), handles a signal that was already aborted before the call, so the function does not start work that nobody wants.

Rule 2: pass the signal down, every time

A signal that stops at the first layer is worthless. When a function calls another async function, forward the same signal. This is the rule people break most, because forgetting it produces no error, only work that continues after the caller has given up.

rule2.jsJavaScript
async function loadUser(id, { signal } = {}) {
  await new Promise((resolve) => setTimeout(resolve, 30));
  signal?.throwIfAborted();
  return { id, name: `user ${id}` };
}

async function loadTeam(teamId, { signal } = {}) {
  const ids = [1, 2, 3];
  const members = [];
  for (const id of ids) {
    members.push(await loadUser(id, { signal })); // forwarded
  }
  return { teamId, members };
}

const controller = new AbortController();
setTimeout(() => controller.abort(new Error("page closed")), 40);

try {
  await loadTeam(7, { signal: controller.signal });
} catch (error) {
  console.log(error.message);
}
Text
page closed

The abort fired during the second user's load. That loadUser checked the signal after its wait and threw, so the third user was never requested. Without the forwarded signal, loadTeam would have loaded all three users and returned a team that nobody was waiting for.

Rule 3: check between steps

Between two awaits is a good place for a check, since that is where one unit of work ended and the next has not begun. A signal cannot interrupt a synchronous stretch, so long loops need their own checks.

rule3.jsJavaScript
export async function processAll(items, handle, { signal } = {}) {
  const results = [];
  for (const item of items) {
    signal?.throwIfAborted(); // stop before starting the next unit
    results.push(await handle(item, { signal }));
  }
  return results;
}

A reasonable granularity is one check per unit of work that takes noticeable time. Checking inside a tight arithmetic loop adds cost for no gain, while checking once per request or per file keeps cancellation prompt.

Rule 4: clean up in finally

When cancellation arrives as a thrown reason, code after the awaited call does not run. Anything that must be released, such as an open file, a timer or a lock, has to be released in a finally block, which runs on success, failure and abort alike.

rule4.jsJavaScript
import { open } from "node:fs/promises";

export async function copyHead(path, bytes, { signal } = {}) {
  const file = await open(path, "r");
  try {
    signal?.throwIfAborted();
    const buffer = Buffer.alloc(bytes);
    const { bytesRead } = await file.read(buffer, 0, bytes, 0);
    return buffer.subarray(0, bytesRead);
  } finally {
    await file.close(); // runs even when the signal aborted
  }
}

If the cleanup line sat after the return, a canceled call would leak the file handle, and a service that cancels often would eventually run out of handles.

Rule 5: abort is a normal outcome

A canceled operation is not an error to report. A user who closed a dialog does not want a red message, and monitoring should not count it as a failure. Give callers one way to recognize it and handle it at the boundary.

rule5.jsJavaScript
export function isAbort(error) {
  return error?.name === "AbortError" || error?.name === "TimeoutError";
}

async function run(task, signal) {
  try {
    return await task(signal);
  } catch (error) {
    if (isAbort(error)) return null; // quiet: the caller asked for this
    throw error;
  }
}

const controller = new AbortController();
const pending = run(
  (signal) =>
    new Promise((resolve, reject) => {
      signal.addEventListener("abort", () => reject(signal.reason), { once: true });
    }),
  controller.signal
);
controller.abort();
console.log(await pending);
Text
null

If you abort with a custom reason, such as new ShutdownError(), extend the check to recognize it, or make your reasons instances of a shared base class. Matching on the error's name is safer than matching on its message.

Rule 6: make timeouts part of the same mechanism

A deadline is just another source of cancellation. Instead of adding a separate timeout parameter to every function, let callers build a signal that includes the deadline, with AbortSignal.timeout(ms), and pass it like any other. Combine it with the user's signal using AbortSignal.any, and the function sees one signal with two possible causes. This keeps function signatures small and moves the policy to the caller, which knows the budget.

A function that is hard to cancel, and its fix

Here is a typical function written without cancellation in mind: it polls for a result with a sleep in a loop. It cannot be stopped until it finishes.

hard.jsJavaScript
async function waitForResult(check) {
  while (!(await check())) {
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
}

The fixed version accepts a signal, checks it each round, and makes the sleep itself cancelable, so an abort takes effect at once instead of at the end of the current sleep.

easy.jsJavaScript
function sleep(ms, signal) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const timer = setTimeout(resolve, ms);
    signal?.addEventListener(
      "abort",
      () => {
        clearTimeout(timer);
        reject(signal.reason);
      },
      { once: true }
    );
  });
}

export async function waitForResult(check, { signal } = {}) {
  while (!(await check({ signal }))) {
    await sleep(1000, signal);
  }
}

const controller = new AbortController();
setTimeout(() => controller.abort(new Error("stop")), 20);

try {
  await waitForResult(async () => false, { signal: controller.signal });
} catch (error) {
  console.log(error.message);
}
Text
stop

The abort at 20 milliseconds ended the wait immediately, though the sleep was set for a full second. That is the payoff of the rules: cancellation costs a few lines per function and works through all the layers.

Cancellation in a whole feature

Walk through a realistic case to see how the rules compose. A report page loads a summary, then three charts, each of which calls two endpoints. The page creates one AbortController when it opens and passes its signal to the loader. The loader forwards it to the summary request and to each chart function, which forward it to their requests. When the user navigates away, the page calls abort() once, and every request in flight is canceled, every pending sleep ends and every function that is between steps stops at its next check. Nothing in the middle needed to know about navigation: it only needed to accept and forward a signal. That is the benefit of making the signal a convention instead of a feature added later.

Compare that with the alternative of adding a cancel() method to each object. Each object would need to track what it started, and the page would need to call every one of them in the right order. A shared signal inverts the relationship: the work listens, and the owner decides. It also composes with the platform, since fetch, timers from node:timers/promises, streams and event listeners already accept signals.

What to do about code you do not control

Some code will not accept a signal: older libraries, callback APIs, third-party clients. You can still protect the rest of the system. Wrap the call in a helper that races it against the signal, so your function stops waiting and moves on, and document that the underlying work may continue. For libraries that expose their own cancel method, such as a database client that can cancel a running query, call it from an abort listener, so the signal drives the library's mechanism. Prefer libraries that accept signals when you choose dependencies, and open an issue when one that should does not.

Testing cancellation

Cancellation behavior is easy to test and often untested. For each cancelable function write three cases. First, an already-aborted signal: the function should reject at once, and should not call its dependencies, which you can check with a stub that records calls. Second, an abort during a wait: use a stub dependency that waits on a deferred promise, abort the signal, and assert that the function rejects with the reason and that cleanup ran, using a flag set in the dependency's finally. Third, an abort after completion: the function should have returned its value, and the late abort should have no effect and cause no unhandled rejection. These three cases catch missing forwarding, missing cleanup and leaked listeners.

Add one test at the top of the feature, with the real call chain and fake leaf dependencies, that aborts and asserts that none of the leaves is still running. That test is the one that fails when a new helper is added in the middle of the chain without a signal parameter, which is how coverage of the convention erodes over time.

Taggedbeginner
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.