Abort and timeouts

AbortController

AbortController ships as a global since Node 15, so no import is needed. Create one controller per task and pass its signal down. Calling abort tells every listener that the work is no longer wanted. The listener runs at once, so the program prints its message.

const ctrl = new AbortController(); ctrl.signal.addEventListener("abort", () => { console.log("aborted"); }); ctrl.abort();

aborted

Abort after ms

Pair the controller with a timer to bound the wait. Start the timer next to the work and call abort when it fires. The worker sees the abort event and can stop early. The timer fires after a second and the listener prints its message.

const ctrl2 = new AbortController(); const timer = setTimeout(() => { ctrl2.abort(); }, 1000); ctrl2.signal.addEventListener("abort", () => { console.log("timed out"); });

timed out

Cancel without fetch

A global fetch is not in every runtime, but http and https requests accept the same signal. Pass the signal in the request options. Destroy the request on abort so sockets do not linger. The program starts a local server that answers late, cancels its own request, prints the name of the abort error and closes the server.

import * as http from "node:http"; async function main(): Promise<void> { const server = http.createServer((_req, res) => { setTimeout(() => { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("late answer"); }, 500); }); await new Promise<void>((resolve) => { server.listen(0, "127.0.0.1", resolve); }); const address = server.address(); const port = typeof address === "object" && address !== null ? address.port : 0; const ctrl3 = new AbortController(); const req = http.get(`http://127.0.0.1:${port}/`, { signal: ctrl3.signal }, (res) => { res.resume(); }); const failed = new Promise<void>((resolve) => { req.on("error", (err: Error) => { console.log(err.name); resolve(); }); }); ctrl3.signal.addEventListener("abort", () => { req.destroy(); }); ctrl3.abort(); await failed; await new Promise<void>((resolve) => { server.close(() => resolve()); }); } main();

AbortError

Clean timers

Always clear the timeout once the work settles. A live timer keeps the process awake and fires a late abort by surprise. Put clearTimeout in a finally block so both success and failure clean up. The work is already done, the timer is cleared in the finally block, and the program prints the value.

async function guarded(work: Promise<string>): Promise<string> { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 1000); try { return await work; } finally { clearTimeout(timer); } } async function main(): Promise<void> { const value = await guarded(Promise.resolve("done")); console.log(value); } main();

done

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does AbortController give a task?

    Answer

    A signal that reports when the work is no longer wanted

    The controller owns the signal, and abort turns that signal into an event every listener can see.

  2. What is the signal of a controller for?

    Answer

    Passing it to work and to a listener, so one abort call reaches all of them

    The same signal goes into the request options and into the listeners, which is how one abort stops several pieces.

  3. What does abort do to a request that was given the signal?

    Answer

    It ends the request and the request reports an AbortError

    Aborting rejects the request with an error named AbortError, which is what a catch around the await sees.

  4. Why is clearTimeout put in a finally block?

    Answer

    So the timer is cleared on both the success and the failure path

    The finally block runs whatever the work does, so no path leaves a live timer behind.

  5. What does this program print? const ctrl = new AbortController(); ctrl.signal.addEventListener("abort", () => { console.log("aborted"); }); ctrl.abort();

    Answer

    aborted

    The listener is registered before abort is called, so the event reaches it and it prints its message.

  6. What does this program print? const ctrl2 = new AbortController(); const timer = setTimeout(() => { ctrl2.abort(); }, 1000); ctrl2.signal.addEventListener("abort", () => { console.log("timed out"); });

    Answer

    timed out

    The timer calls abort once, the listener runs and prints its text, and no process is left to print more.

  7. What does this program print? ``import * as http from "node:http"; async function main(): Promise<void> { const server = http.createServer((_req, res) => { setTimeout(() => { res.writeHead(200, { "Content-Type": "text/plain" }); res.end("late answer"); }, 500); }); await new Promise<void>((resolve) => { server.listen(0, "127.0.0.1", resolve); }); const address = server.address(); const port = typeof address === "object" && address !== null ? address.port : 0; const ctrl3 = new AbortController(); const req = http.get(http://127.0.0.1:${port}/, { signal: ctrl3.signal }, (res) => { res.resume(); }); const failed = new Promise<void>((resolve) => { req.on("error", (err: Error) => { console.log(err.name); resolve(); }); }); ctrl3.signal.addEventListener("abort", () => { req.destroy(); }); ctrl3.abort(); await failed; await new Promise<void>((resolve) => { server.close(() => resolve()); }); } main();``

    Answer

    AbortError

    The abort ends the request before the delayed answer, and the error handler prints the name of the abort error.

  8. What does this program print? async function guarded(work: Promise<string>): Promise<string> { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 1000); try { return await work; } finally { clearTimeout(timer); } } async function main(): Promise<void> { const value = await guarded(Promise.resolve("done")); console.log(value); } main();

    Answer

    done

    The work is already fulfilled, so the await returns its value and the finally block clears the timer.

  9. A program calls ctrl.abort() but never clears its setTimeout. What does the forgotten timer do?

    Answer

    A live timer keeps the process awake and fires a late abort

    A pending timer holds the event loop open, and when it fires its abort comes after the work it was meant to bound.

  10. What does the compiler say about this program? const ctrl = new AbortController(); const signal: boolean = ctrl.signal; console.log(signal);

    Answer

    error TS2322: Type 'AbortSignal' is not assignable to type 'boolean'.

    The signal is an AbortSignal object, not a flag: its state is read with aborted or through the abort event.

Article author: Arthur Isaev