AbortController

AbortController and AbortSignal cancel in-progress asynchronous operations. Create a controller, pass its signal to an operation (such as fetch()), and call abort() to cancel it. Every listener of the signal’s abort event runs, and operations watching the signal reject with the signal’s reason.

  • new AbortController() creates a controller.
  • controller.signal is the AbortSignal to hand to operations.
  • controller.abort(reason) fires the signal: the abort event runs and signal.aborted becomes true. The default reason is a DOMException named AbortError.
  • signal.aborted reports whether the signal has fired.
  • signal.reason is the abort reason, or undefined before abort.
  • signal.throwIfAborted() throws the reason when the signal has aborted.
  • signal.addEventListener("abort", listener) (and the other EventTarget methods) register listeners; they can be removed with removeEventListener().
  • signal.onabort is a shorthand for an abort listener.
  • AbortSignal.abort(reason) creates an already-aborted signal.
  • AbortSignal.timeout(milliseconds) creates a signal that aborts with a TimeoutError after the delay.
  • AbortSignal.any(signals) creates a signal that aborts when any of the input signals aborts.

Usage#

Cancelling a fetch after a timeout:

try {
  const response = await fetch("https://httpbin.org/delay/5", {
    signal: AbortSignal.timeout(5000),
  });
  console.log(await response.text());
} catch (err) {
  if (err.name === "TimeoutError") {
    console.log("request timed out");
  }
}

Cancelling with your own reason:

const controller = new AbortController();

setTimeout(() => controller.abort("job cancelled"), 1000);

try {
  await fetch("https://httpbin.org/delay/5", {
    signal: controller.signal,
  });
} catch (err) {
  console.log(err); // job cancelled
}

Combining a timeout with a manual stop:

const stop = new AbortController();
const signal = AbortSignal.any([
  AbortSignal.timeout(5000),
  stop.signal,
]);

try {
  await fetch("https://httpbin.org/delay/5", { signal });
} catch (err) {
  console.log(signal.reason);
}

Checking before doing work:

function save(record, signal) {
  signal.throwIfAborted();
  return fs.writeFile("/record.json", JSON.stringify(record));
}

Documentation#