Cooperative cancellation with AbortController
How it works
AbortController exposes a signal and an abort(reason) operation. The signal becomes aborted once, retains the reason and dispatches an abort event. throwIfAborted() throws that reason if already aborted. An API must explicitly observe the signal; abort cannot forcibly stop arbitrary JavaScript or change a settled promise. Use { once: true } or remove listeners when work completes. AbortSignal.any and timeout provide host-specific composition conveniences; check availability.
Example 1
const c = new AbortController();c.signal.addEventListener("abort", () => console.log(c.signal.reason), {once:true});c.abort("stop"); c.abort("again");console.log(c.signal.aborted);Expected output in the tested environment:
stoptrueThe first abort sets the reason and dispatches the event only once.
Example 2
const c = new AbortController(); c.abort(new Error("canceled"));try { c.signal.throwIfAborted(); } catch (e) { console.log(e.message); }Expected output in the tested environment:
canceledAlready aborted signals can be checked before starting work.
Common mistake
A promise itself has no general-purpose abort method. Pass the signal to an operation designed to observe it.
Practice
Build a controlled operation that rejects on an abort event, checks already-aborted signals and removes its listener after normal completion.
Run this practice in the documented local environment. ByteMind module and asynchronous grader support is not yet verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Cooperative cancellation with AbortController — Knowledge Check
Reason about the concept and predict its behavior in the indicated environment.
What must an operation do for AbortController to stop its work?
Does calling abort twice replace the signal reason?
What does throwIfAborted do when the signal is already aborted?
For Cooperative cancellation with AbortController, what is the console output of example 1 in Node.js 22.16.0?
const c = new AbortController();c.signal.addEventListener("abort", () => console.log(c.signal.reason), {once:true});c.abort("stop"); c.abort("again");console.log(c.signal.aborted);For Cooperative cancellation with AbortController, what is the console output of example 2 in Node.js 22.16.0?
const c = new AbortController(); c.abort(new Error("canceled"));try { c.signal.throwIfAborted(); } catch (e) { console.log(e.message); }