bhylu.com

Advertisements

Node.js AbortController

A timeout should stop or cancel the underlying operation when the API supports it. Racing a promise against a timer alone does not necessarily release resources.

How it works

AbortController communicates a cancellation request through a signal. Each receiving API decides how it handles that signal; not every custom promise becomes cancellable merely because a signal exists nearby. Use owned controllers when a caller must be able to cancel, and clear ordinary timers when their scope ends. This fixture cancels the promise-based timer before it can complete and observes the expected AbortError rather than leaving a rejection unhandled.

Run the code

Run this example locally with Node.js. The exact sources are reviewed on Node 22.15.1 and Node 24.22.1 unless a specialised lab states otherwise. Save the complete source as cancellation.mjs in a separate empty exercises folder and run node cancellation.mjs. There is no Node.js browser runner on Bhylu; the plain JavaScript playground does not provide these filesystem, server or process APIs.

Download the complete source. Ordinary Node scripts need no Apache, PHP or MySQL service. File examples own their temporary folders; network fixtures use loopback and available temporary ports.

Example

cancellation.mjs

import { setTimeout as delay } from 'node:timers/promises';
const controller = new AbortController();
const waiting = delay(1000, 'too late', { signal: controller.signal });
controller.abort();
try {
  await waiting;
} catch (error) {
  console.log(error.name);
}
console.log(controller.signal.aborted);

Expected result

AbortError
true

The timer is cancelled through an API that accepts the signal. Cancellation is not a transaction rollback for work already committed; a network or database request may require its own idempotency and reconciliation policy.

Use the Node.js API reference for the precise version contract.