Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 133 ยท Asynchronous Programming

AbortController and Cancellation

Cancel async work in Node.js with AbortController and AbortSignal - fetch, timers, fs, events and streams, AbortSignal.timeout and any, cancellable functions, cleanup and error names.

Promises have no built-in way to stop. Once you start fetch(url) or readFile(path), the promise only tells you what happened; it offers no handle to say "never mind". But real programs need to cancel: the user closes a tab, a request is too slow, a client disconnects, the server is shutting down. Without cancellation, abandoned work keeps running, holding sockets, memory and CPU for results nobody wants.

The web platform solved this with two small objects that Node.js shares: an AbortController (the thing you hold, which can trigger an abort) and an AbortSignal (the thing you pass to operations, which tells them to stop). This lesson explains both, shows which Node APIs accept a signal, and builds cancellable functions of your own. It follows naturally from the timeouts in Concurrency Control and Queues.

Controller and signal

You create a controller, take its signal, and give that signal to as many operations as you like. Calling controller.abort() flips the signal to the aborted state, fires its abort event once, and records a reason.

Node.js The anatomy of an abort

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The signal is one-way and one-shot: once aborted, it stays aborted, and a new operation needs a new controller. The controller is the capability to cancel; the signal is the ability to observe. Keep the controller private and hand out only the signal, so callees cannot cancel each other's work.

You can also check the state without listening: signal.throwIfAborted() throws the reason if the signal is already aborted. It is the quickest guard at the top of a function and between steps of long work.

Signals in Node APIs

Most promise-based Node APIs take { signal } in their options. When the signal aborts, the operation stops as soon as it can and the promise rejects with an error whose name is 'AbortError'.

Node.js Cancelling timers, files and events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

All three reject with AbortError, and the Node-specific code is ABORT_ERR. Note the second case: passing AbortSignal.abort() (a signal that is already aborted) means the operation rejects without doing any work. That is the correct behavior for any cancellable function: check first, then start.

fetch and HTTP

fetch accepts a signal and cancels the request: the connection is dropped and the promise rejects. Here we run a small server on loopback that answers after a long delay, and cancel from the client.

Node.js Cancelling a slow fetch

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Two useful facts show up. The server's req.on('close') fires when the client cancels, so the server can stop its own work too: cancellation propagates across the network. And the name of the error differs: a manual abort() gives AbortError, while AbortSignal.timeout gives TimeoutError. We look at the difference below.

Timeouts and combining signals

AbortSignal.timeout(ms) returns a signal that aborts itself after ms milliseconds with a TimeoutError. It needs no controller and does not keep the process alive. AbortSignal.any([a, b]) returns a signal that aborts as soon as any of its inputs does, and reports the first one's reason. Together they answer the common question "cancel when the user says so or after 5 seconds".

Node.js Combining a user cancel with a timeout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The reason tells you why work stopped, which matters for what you do next: a user cancel might need silence, a timeout probably needs an error message or a retry. AbortSignal.any was added in Node 20.3, so it exists in every maintained version.

Writing cancellable functions

To make your own function cancellable, accept { signal } in an options object and do four things:

  1. Check signal?.throwIfAborted() before starting.
  2. Pass the signal on to every cancellable call you make (so cancellation reaches the bottom).
  3. Check the signal between the steps of long loops.
  4. Clean up (timers, listeners, open handles) whether you finish or abort.
Node.js A cancellable batch function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

throwIfAborted() throws the signal's reason. When you called abort() with no argument the reason is an AbortError; when you gave a custom Error it throws that error directly. A downstream API (like sleep) that rejects because of the signal throws an AbortError, with the original reason in error.cause. Handle both when you print messages, as the output above shows.

Making an existing promise abortable

If you have a promise-returning function that cannot take a signal, you can only stop waiting for it. This helper rejects when the signal fires, but the underlying work continues, so use it only when nothing better exists:

NODE
function abortable(promise, signal) {
  return new Promise((resolve, reject) => {
    signal.throwIfAborted();
    signal.addEventListener('abort', () => reject(signal.reason), { once: true });
    promise.then(resolve, reject);
  });
}

Clean up your listeners

Every addEventListener('abort', ...) on a long-lived signal that is not removed stays in memory. Use { once: true } as above, or remove the listener in a finally. The related option { signal } on addEventListener goes the other way: it lets a signal remove listeners for you.

Node.js One abort removes many listeners

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This pattern is wonderful for components with a lifetime: create a controller when something starts, register everything with its signal, and one abort() tears it all down.

Streams and servers

Stream helpers take signals as well. stream.pipeline(..., { signal }) destroys every stream in the chain and rejects with AbortError; readable.destroy() is the underlying call. In an HTTP server, req.on('close') or a signal tied to the connection lets a handler stop expensive work when the client disconnects. A graceful shutdown typically creates one controller for the whole process, aborts it on SIGTERM, and passes the signal to every long-running job.

Node.js Aborting a pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

(We print only whether items arrived, not how many: the count depends on timing.)

AbortError, TimeoutError and DOMException

Aborts are reported as DOMException objects (the same class browsers use) with a name: 'AbortError' for a normal abort and 'TimeoutError' for AbortSignal.timeout. Node's own APIs wrap the reason into an error with name: 'AbortError' and code: 'ABORT_ERR'. So do not test with instanceof; test the name (or the signal) instead.

Node.js Telling cancellation from real failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The distinction matters in logs and metrics. A user closing a page is normal; a database failure is not. Logging every AbortError as an error floods dashboards with noise and hides the real problems.

Cancelling is cooperative. An abort only works if the code doing the work looks at the signal. Pure JavaScript loops, a synchronous JSON.parse of a huge string, or a CPU-bound calculation will not stop on their own; check the signal inside long loops or move that work to a worker thread you can terminate.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the relationship between AbortController and AbortSignal?

    You keep the controller, which can call abort(), and give the signal to the code that should be cancellable.
  2. 2. What does AbortSignal.timeout(100) do?

    AbortSignal.timeout creates a self-aborting signal, which needs no controller.
  3. 3. How do you cancel an operation when either the user clicks cancel or 5 seconds pass?

    AbortSignal.any returns a signal that aborts when the first of its inputs aborts, and carries that input's reason.
  4. 4. Why should you check err.name instead of using instanceof to detect cancellation?

    Aborts show up as DOMException or wrapped errors depending on the API, so the name is the stable thing to test.
  5. 5. A function runs a long synchronous loop of 50 million iterations. Why does abort() not stop it?

    An abort changes the signal's state; code has to look at it. A busy synchronous loop never yields, so it must check the signal itself.

Summary

  • AbortController triggers cancellation; AbortSignal is what you pass to operations. A signal aborts once and has a reason.
  • Many Node APIs accept { signal }: timers, fs/promises, events.once, streams, fetch and http; they reject with an AbortError.
  • AbortSignal.timeout(ms) makes deadlines easy; AbortSignal.any([...]) combines signals.
  • Cancellable functions check the signal first, pass it down, check between steps, and clean up.
  • addEventListener(..., { signal }) removes listeners when the signal aborts.
  • Test err.name for AbortError or TimeoutError, and do not report ordinary cancellation as a failure.
  • Cancellation is cooperative; busy loops must look at the signal.

Next: Async Iterators and Generators