Skip to content
jshacks.dev
Functions

How to Write a Function That Can Be Cancelled

Write a JavaScript function that can be cancelled with AbortSignal, check it between steps, stop timers and fetch, and clean up resources. Node.js 24.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, TypeScript, npm, Vite and Node.js logos.

A user types in a search box, and the request for "ja" is still in flight when the request for "jav" starts. A page navigates away while its data loads. A job runs past its deadline. In each case the work should stop, because continuing wastes resources and, worse, the late result of the old request may overwrite the newer one. JavaScript's standard answer is AbortController and AbortSignal: the caller holds the controller and calls abort(), and the function receives the signal and watches it. This post shows how to write a function that honors a signal on Node.js 24: how to accept one, check it between steps, stop a timer and a fetch, release resources, tell an abort from a real failure and combine signals for timeouts. For the cancellation of generators, see cancelling a generator early.

The two halves

The caller creates an AbortController and passes controller.signal to the function. When the caller decides to stop, controller.abort() flips the signal to the aborted state, sets signal.reason and fires an abort event. The function never aborts itself through the signal. It only observes.

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

console.log(signal.aborted);

signal.addEventListener("abort", () => console.log("event fired:", signal.reason.name));

controller.abort();

console.log(signal.aborted, signal.reason.name);
Text
false
event fired: AbortError
true AbortError

By default, abort() with no argument sets the reason to a DOMException named AbortError. You can pass your own reason, for example controller.abort(new Error("user navigated away")), and it becomes signal.reason. A signal that has been aborted stays aborted: it cannot be reset, so each cancellable operation gets a fresh controller.

Checking between steps

The simplest cancellable function does its work in steps and checks the signal at each boundary. signal.throwIfAborted() throws the reason if the signal is aborted, and does nothing otherwise.

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 * 2);
  }

  return done;
}

const c = new AbortController();

const run = processAll([1, 2, 3, 4, 5], { signal: c.signal });

setTimeout(() => c.abort(), 12);

try {
  await run;
} catch (error) {
  console.log(error.name);
}
Text
AbortError

The abort fires at 12 milliseconds, partway through the third item, and the next check at the top of the loop throws. The optional chain signal?. lets callers omit the signal altogether. The function is cancellable only at the points where it looks, which is the central limitation: a long synchronous loop without checks cannot be interrupted, because nothing else runs until it finishes. Put a check inside any loop that could run long, and for very heavy computation, do it in chunks that yield to the event loop between them.

Stopping a pending wait

Checking between steps leaves the wait itself uninterrupted: if the abort arrives while a ten-second sleep is pending, the function still waits the full ten seconds before noticing. A cancellable wait listens for the event and rejects at once.

JavaScript
function sleep(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) {
      reject(signal.reason);
      return;
    }

    const timer = setTimeout(() => {
      signal?.removeEventListener("abort", onAbort);
      resolve();
    }, ms);

    function onAbort() {
      clearTimeout(timer);
      reject(signal.reason);
    }

    signal?.addEventListener("abort", onAbort, { once: true });
  });
}

const stop = new AbortController();
const started = performance.now();

setTimeout(() => stop.abort(), 10);

try {
  await sleep(10_000, { signal: stop.signal });
} catch (error) {
  console.log(error.name, performance.now() - started < 1000);
}
Text
AbortError true

The sleep rejected in about ten milliseconds instead of ten seconds. Three details matter. The early check handles a signal that is already aborted, because the event will never fire for it. clearTimeout stops the timer, so the process is not kept alive. And the listener is removed when the timer completes normally, otherwise a long-lived signal collects one listener per call and leaks.

Node.js ships this function: import { setTimeout as delay } from "node:timers/promises" and await delay(ms, undefined, { signal }) do the same, so in real code use that instead of writing your own.

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

const ac = new AbortController();
setTimeout(() => ac.abort(), 5);

try {
  await delay(5000, undefined, { signal: ac.signal });
} catch (error) {
  console.log(error.name, error.code);
}
Text
AbortError ABORT_ERR

The error carries the code ABORT_ERR, which is Node.js's own marker for an aborted operation.

Passing the signal to fetch and other APIs

Many built-in APIs accept a signal directly: fetch, fs.promises.readFile, child_process.execFile, EventTarget.addEventListener, timers and streams. When your function calls one of them, pass the signal through, and the cancellation reaches the lowest level.

JavaScript
async function loadJson(url, { signal } = {}) {
  const response = await fetch(url, { signal });

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }

  return response.json();
}

When the signal aborts during the request, fetch rejects with an AbortError and the connection is dropped, so no data is downloaded for nothing. This is the pattern for the search box: keep the controller of the last request, abort it when a new keystroke arrives and start a new one. The stale response can never overwrite the fresh one, because the stale request was cancelled, and its promise rejected.

A function that only forwards the signal needs no checks of its own. Forwarding is the cheapest way to be cancellable, and the first thing to look for.

Telling an abort from a failure

A cancelled call rejects, and a catch block that logs every error as a failure will report normal cancellations as problems. Distinguish them by name.

JavaScript
function isAbort(error) {
  return error?.name === "AbortError";
}

async function search(query, signal) {
  try {
    await sleep(20, { signal });
    return [`result for ${query}`];
  } catch (error) {
    if (isAbort(error)) return null;
    throw error;
  }
}

const first = new AbortController();
const p1 = search("ja", first.signal);
first.abort();

console.log(await p1);
console.log(await search("jav", new AbortController().signal));
Text
null
[ 'result for jav' ]

The cancelled search returned null, a value the caller can ignore, and the real search returned results. Choosing between returning a sentinel and letting the AbortError propagate is a design decision. Propagating is more honest and works naturally with try/finally, while a sentinel simplifies call sites that do not care. If you set a custom reason, check signal.aborted instead of the name, since the error may be whatever the caller passed.

Cleaning up

A cancelled function must release what it holds: close files, clear timers, remove listeners, roll back a partial state. Use finally, which runs whether the function succeeds, fails or is cancelled.

JavaScript
async function withTempResource(signal) {
  const log = [];
  log.push("open");

  try {
    await sleep(50, { signal });
    log.push("work done");
  } finally {
    log.push("closed");
  }

  return log;
}

const cancel = new AbortController();
setTimeout(() => cancel.abort(), 5);

try {
  await withTempResource(cancel.signal);
} catch (error) {
  console.log(error.name);
}

const log = await withTempResource(new AbortController().signal);
console.log(log);
Text
AbortError
[ 'open', 'work done', 'closed' ]

In the cancelled run, the sleep rejected, finally ran and closed the resource, and the error continued to the caller. In the normal run the three steps happened in order. Cleanup in finally is the part that makes cancellation safe, and the part most often forgotten.

Timeouts and combining signals

A timeout is a cancellation triggered by the clock. AbortSignal.timeout(ms) makes a signal that aborts itself after that long, with a TimeoutError reason. AbortSignal.any([a, b]) combines signals, aborting when any of them does.

JavaScript
const userCancel = new AbortController();
const combined = AbortSignal.any([userCancel.signal, AbortSignal.timeout(20)]);

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

The timeout fired first, so the reason is a TimeoutError, not an AbortError. A function that wants to treat both the same checks signal.aborted rather than the name. This is how you give every request a deadline while still letting the user cancel: combine the user's signal with a timeout and pass the result down.

Designing the API

A few conventions keep cancellable functions predictable. Take the signal in an options object under the name signal, as the platform APIs do, so callers can pass it to yours and to fetch in the same style. Do not create a controller inside your function unless you also hand it back, since the caller then has no way to cancel. Throw or reject with the signal's own reason, using signal.throwIfAborted() or reject(signal.reason), so the cause the caller supplied reaches them intact.

Finally, document what cancellation guarantees. Does cancelling undo the work already done, or only stop further work? A database transaction can roll back, while a file already written stays. Say which, because callers will otherwise assume the stronger promise.

Testing it

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

test("rejects at once when already aborted", async () => {
  const c = new AbortController();
  c.abort();

  await assert.rejects(sleep(1000, { signal: c.signal }), { name: "AbortError" });
});

test("stops between steps", async () => {
  const c = new AbortController();
  const run = processAll([1, 2, 3], { signal: c.signal });

  c.abort();

  await assert.rejects(run, { name: "AbortError" });
});

test("cleanup runs on abort", async () => {
  const c = new AbortController();
  c.abort();

  await assert.rejects(withTempResource(c.signal));
});
Text
ℹ tests 3
ℹ pass 3
ℹ fail 0
Taggedasync
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

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