Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

AbortController and AbortSignal: Request cancellation and read its state

Pass `controller.signal` to an operation that supports cancellation, call `controller.abort()` to request it, and read `signal.aborted` to inspect the signal rather than the operation's outcome.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

const controller = new AbortController();
const signal = controller.signal;
const aborted = signal.aborted;

// Two call forms; choose one for the first abort:
controller.abort();
controller.abort(reason);

Create a new AbortController() and keep the controller in the code that decides when to cancel. The read-only instance property controller.signal always returns the same AbortSignal object for that controller. Pass it to an API that accepts it, for example through fetch(url, { signal }). Several operations can share one signal if they should be cancelled together.

signal.aborted is a read-only boolean property, not a method. It starts as false. The first call to controller.abort() or controller.abort(reason) synchronously changes the signal's state to true and dispatches its abort event before returning undefined. signal.reason holds the supplied value; if the argument is omitted or undefined, it holds a DOMException named AbortError.

Later calls neither replace the reason nor dispatch another event. The signal cannot be reset: create a new controller for a new cancellation lifetime. The static method AbortSignal.abort() is different: it creates a new, already-aborted signal rather than changing an existing controller's signal.

Cancellation is cooperative. aborted === true describes the signal; it does not confirm that an operation stopped or undo completed work. In your own promise-based API, check the signal before starting, handle a later abort event, reject any still-pending promise with signal.reason, and remove the listener on normal completion. These are web platform APIs, not part of ECMAScript 2024; check support in your target runtime.

Examples

{
  const controller = new AbortController();
  const signal = controller.signal;

  console.log(`before: ${signal.aborted}`);
  signal.addEventListener("abort", () => {
    console.log(`event: ${signal.aborted}`);
  });

  controller.abort("superseded");
  controller.abort("ignored");
  console.log(`after: ${signal.aborted}, ${signal.reason}`);
}

Result

before: false
event: true
after: true, superseded

The line `event: true` shows that the state has already changed when the event listener runs. The second call does not fire another event or replace the reason `superseded`.

Related lessons

  • JavaScript · Lesson 4 · Advanced · Version: 4

Sources