Racing a promise against a timer is the usual first attempt at a timeout. It looks right, and it leaves the slow work running after you have already told the caller it failed.

javascript
const timeout = new Promise((_, reject) => {
  setTimeout(() => reject(new Error('operation timed out')), 10000);
});

await Promise.race([fooTask(), timeout]);

fooTask might be a file read, an API call or a database query. Two things go wrong with this code:

  • When the timer wins, fooTask() keeps going. The socket stays open and the query keeps running, and nobody is waiting for the result.
  • When fooTask() wins, the timer is still scheduled. It fires later and rejects a promise nobody listens to. That is harmless once, and a slow leak in a hot path.

AbortController fixes both. This post covers the pieces, the short way to write a timeout in current Node, and the mistakes that still catch people.

It’s part of the async JavaScript series.

AbortController in Node.js

Quick answer

Pass a signal to the work you want to cancel, and abort it from outside. AbortController has been global since Node 15, and AbortSignal.timeout() has been available since Node 17.3 and 16.14. You no longer need to hand-roll the timer.

javascript
const res = await fetch(url, { signal: AbortSignal.timeout(5000) });

If the request takes longer than five seconds, fetch rejects with a TimeoutError and the connection is torn down. Nothing is left running.

The two objects

AbortController has one method and one property. controller.abort() flips the switch. controller.signal is the AbortSignal you hand to whatever should listen.

AbortSignal is an EventTarget. It emits a single abort event, and has a boolean aborted and a reason. The API follows the browser AbortController, so the same code works on the server and in the page.

Aborting is cooperative. The signal does nothing by itself. The function that receives it has to check it or listen for the event, which is why built-in APIs matter: they already do.

Cancelling work you wrote yourself

Here is a small task that honours a signal, with a manual abort after 20 ms. I ran this on Node 24.

javascript
import { setTimeout as sleep } from 'node:timers/promises';

async function slow(ms, { signal } = {}) {
  await sleep(ms, undefined, { signal });
  return 'done';
}

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

try {
  await slow(500, { signal: ac.signal });
} catch (err) {
  console.log(err.name, err.code); // AbortError ABORT_ERR
}

The timer from timers/promises accepts a signal and rejects as soon as it fires. For your own loops or multi-step jobs, check signal.throwIfAborted() between steps. It throws the signal’s reason when aborted and does nothing otherwise.

A deadline in one line

AbortSignal.timeout(ms) creates a signal that aborts itself. No controller, no clearTimeout, and the timer does not keep the process alive.

javascript
for (const ms of [50, 500]) {
  try {
    console.log(await slow(ms, { signal: AbortSignal.timeout(100) }));
  } catch (err) {
    console.log(err.name);
  }
}
// done
// AbortError

One wrinkle: the error name depends on who rejects. fetch rejects with TimeoutError when the deadline passes, but timers/promises reports a plain AbortError. If you branch on err.name, test both, or read signal.reason.

Combining a deadline with a user cancel

A request often has two reasons to stop: a deadline, and the client closing the connection. AbortSignal.any() (Node 20.3+) merges them.

javascript
app.get('/report', async (req, res) => {
  const ac = new AbortController();
  req.on('close', () => ac.abort());

  const signal = AbortSignal.any([ac.signal, AbortSignal.timeout(8000)]);

  try {
    const rows = await db.query(sql, { signal });
    res.json(rows);
  } catch (err) {
    if (signal.aborted) return;
    throw err;
  }
});

The db.query option is illustrative. Check whether your driver takes a signal. Many recent ones do, and for those that don’t you can still listen for the abort event and call their own cancel method.

Which APIs accept a signal

API Accepts signal
fetch Yes
fs/promises (readFile, writeFile) Yes
timers/promises Yes
events.once, events.on Yes
http.request, child_process.spawn Yes
Most database drivers Check the docs

Mistakes that still catch people

  • Treating abort as failure. Aborting rejects with an error. Log it as an error and your dashboards fill with noise from users who simply closed a tab. Branch on the name, as in the Express example.
  • Reusing a controller. A signal aborts once. Create a new controller for each operation.
  • Forgetting to clean up listeners. If you call signal.addEventListener('abort', ...) on a long-lived signal, pass { once: true } or remove it afterwards.
  • Passing the signal and ignoring it. Writing { signal } in your function’s signature does nothing unless something inside uses it.

Frequently Asked Questions

Is AbortController available in Node.js? Yes. It is a global from Node 15. AbortSignal.timeout() needs 16.14 or 17.3, and AbortSignal.any() needs 20.3.

Does abort() stop a synchronous loop? No. JavaScript is single-threaded, so nothing can fire while your loop runs. Check signal.aborted inside the loop yourself, or break the work into awaited chunks.

Why does Promise.race not cancel the loser? It only settles with the first result. The other promise carries on and its result is discarded.

What is the difference between AbortError and TimeoutError? AbortError means someone called abort(). TimeoutError means an AbortSignal.timeout() deadline passed. Some APIs report both as AbortError, so read signal.reason when you need to tell them apart.

Thank you for reading and I hope you find it helpful. I sincerely request for your feedback in the comment’s section. You can follow me on twitter @manisuec.