AbortController sends a notification; it cannot force a promise or CPU loop to stop. A callback must inspect the signal, subscribe to it when waiting, and release listeners or timers on either success or abort. A signal may already be aborted before the callback starts.
The library's contract must also say when its outer promise settles. Our final pool stops starting new jobs on first observed failure, aborts active peers, then waits for active callbacks to settle before rejecting. This provides a useful cleanup boundary, but a callback that never settles can prevent the pool from settling forever.
Use signal.throwIfAborted() for a precondition in modern browsers and Node 22+. It throws the signal's reason, which can be any value, not necessarily Error. If your public API preserves that reason, do not accidentally replace it with a later cleanup failure. The example manually aborts a pending timer; no real network access is involved.
Predict, run, and explain
Write the output and trace the important state changes before checking it. Then run the program. Each editor is independent. Async examples end with main() so this editor waits for their work.
async function main() {
function wait(signal) {
signal.throwIfAborted();
return new Promise((resolve, reject) => {
const onAbort = () => {
clearTimeout(timer);
reject(signal.reason);
};
const timer = setTimeout(() => {
signal.removeEventListener("abort", onAbort);
resolve("done");
}, 100);
signal.addEventListener("abort", onAbort, { once: true });
});
}
const controller = new AbortController();
const pending = wait(controller.signal);
controller.abort("stopped");
try {
await pending;
} catch (reason) {
console.log(reason);
}
}
main();Check your prediction
stoppedCancellation cannot settle an uncooperative callback
A signal communicates a request to stop. It does not force a callback to reject or return. A library that promises to await active callbacks must still wait when one ignores its signal. This settlement policy is as important as the decision to stop starting new work.
Pre-abort and pending abort are different paths. The first can prevent work from starting; the second must notify work already in progress and release any installed listener when it settles. Check both paths rather than treating one as evidence for the other.
async function main() {
const controller = new AbortController();
let starts = 0;
controller.abort("stop");
async function work(signal) {
signal.throwIfAborted();
starts++;
}
try {
await work(controller.signal);
} catch (reason) {
console.log(reason);
}
console.log(starts);
}
main();Check your prediction
stop
0The abort check precedes the side effect. Putting it after starts++ would observe cancellation but fail the no-start contract.
async function main() {
const controller = new AbortController();
async function ignoresSignal() {
await Promise.resolve();
return "finished";
}
const work = ignoresSignal();
controller.abort();
console.log(await work);
console.log(controller.signal.aborted);
}
main();Check your prediction
finished
trueThe controller changed state, but the unrelated callback still fulfilled. A public adapter may suppress that late value, yet cannot undo side effects the callback already performed.
Try the rule on new inputs
Write separate pre-abort and mid-flight fixtures. Count starts, verify the exact reason and track listener removal. State whether your library waits for active work before returning cancellation.
Watch the outer promise wait for a peer
The pool's outer promise does not reject the moment a job fails. It first aborts the other active jobs, then waits for all of them to settle. This smaller runAll keeps that rule. Job A ignores its signal and waits on a deferred promise the test controls; job B fails. The test reads a settled flag to prove what has not happened yet. Predict the six lines.
async function main() {
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
async function runAll(jobs) {
const controller = new AbortController();
let firstError;
const running = jobs.map(job =>
job(controller.signal).catch(error => {
if (firstError === undefined) {
firstError = error;
controller.abort(error);
}
throw error;
})
);
const results = await Promise.allSettled(running);
if (firstError !== undefined) throw firstError;
return results.map(result => result.value);
}
const log = [];
const held = deferred();
const outer = runAll([
async signal => {
log.push("A started");
signal.addEventListener("abort", () => log.push("A saw abort"));
await held.promise; // A ignores the signal and keeps going
log.push("A finished");
return "A";
},
async () => {
log.push("B started");
await null;
throw new Error("B failed");
}
]);
let settled = false;
outer.then(
() => (settled = true),
() => (settled = true)
);
await new Promise(resolve => setTimeout(resolve, 0));
log.push(`outer settled before release: ${settled}`);
held.resolve();
try {
await outer;
} catch (error) {
log.push(`outer rejected: ${error.message}`);
}
console.log(log.join("\n"));
}
main();Check your prediction
A started
B started
A saw abort
outer settled before release: false
A finished
outer rejected: B failedB's failure aborts the shared controller, and A's listener runs, but A ignores the signal and keeps awaiting held. Promise.allSettled waits for every job, so outer is still pending after a full timer turn: the settled flag, set from .then, is still false. Only when the test releases A does allSettled finish; then runAll rejects with the first error, not with anything from A. "Settlement" means exactly this order: abort is a request, and the outer promise settles after the last active job does. If A never finished, neither would outer.
Trace the contract before building
Separate three events: notification of failure or abort, stopping further starts, and settlement of already-started work. They can happen at different times. A callback that ignores its signal may continue, and one that never settles can prevent a wait-for-cleanup policy from finishing.
Test pre-abort and abort during a pending operation separately. Preserve the original reason even when it is undefined or a string. Cleanup failures and later peer rejections must not accidentally replace the first observed failure if that is the API's stated policy. A clear limitation is part of a reliable contract.
Your turn
Forward a caller's abort and still wait
Extend runAll(jobs, outerSignal) so the caller can cancel. If outerSignal is already aborted, reject with its reason and start no job. If it aborts while jobs are running, abort the jobs' signal, still wait for every job to settle, then reject with the caller's reason. In every case, remove the listener you added to outerSignal before runAll settles: a caller can reuse one signal for many calls. watchListeners counts the listeners on the caller's signal. Print:
polite started
held started
settled while held: false
held finished
rejected with: user left
listeners left on caller's signal: 0
already aborted: user left, starts: 0async function main() {
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
async function runAll(jobs, outerSignal) {
// TODO: refuse an already-aborted outerSignal, forward its abort to
// controller, reject with its reason, and remove your listener at the end.
const controller = new AbortController();
let firstError;
const running = jobs.map(job =>
job(controller.signal).catch(error => {
if (firstError === undefined) {
firstError = error;
controller.abort(error);
}
throw error;
})
);
const results = await Promise.allSettled(running);
if (firstError !== undefined) throw firstError;
return results.map(result => result.value);
}
// Counts abort listeners currently attached to one signal.
function watchListeners(signal) {
let count = 0;
const add = signal.addEventListener.bind(signal);
const remove = signal.removeEventListener.bind(signal);
signal.addEventListener = (type, fn, options) => {
count += 1;
add(type, fn, options);
};
signal.removeEventListener = (type, fn, options) => {
count -= 1;
remove(type, fn, options);
};
return () => count;
}
const held = deferred();
const user = new AbortController();
const listeners = watchListeners(user.signal);
const outer = runAll(
[
async signal => {
console.log("polite started");
await new Promise((resolve, reject) => {
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
});
},
async () => {
console.log("held started");
await held.promise; // ignores its signal
console.log("held finished");
}
],
user.signal
);
let settled = false;
outer.then(
() => (settled = true),
() => (settled = true)
);
user.abort("user left");
await new Promise(resolve => setTimeout(resolve, 0));
console.log(`settled while held: ${settled}`);
held.resolve();
try {
await outer;
} catch (reason) {
console.log(`rejected with: ${reason}`);
}
console.log(`listeners left on caller's signal: ${listeners()}`);
let starts = 0;
try {
await runAll([async () => starts++], user.signal);
} catch (reason) {
console.log(`already aborted: ${reason}, starts: ${starts}`);
}
}
main();Hint 1: the idea
The caller's signal and the jobs' signal are different objects: runAll owns its controller and the caller owns outerSignal. A small listener on outerSignal that calls controller.abort(outerSignal.reason) connects them, and whatever runAll adds to a signal it does not own, it must also remove.
Hint 2: a first step
Run the starter first: it prints up to held finished and then stops, because nothing ever aborts the polite job, so allSettled never finishes. Add outerSignal.addEventListener("abort", forward, { once: true }) with forward calling controller.abort(outerSignal.reason), and the run reaches rejected with:. Then check what it rejects with, and the listener count.
Show one solution
async function main() {
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
async function runAll(jobs, outerSignal) {
outerSignal.throwIfAborted();
const controller = new AbortController();
const forward = () => controller.abort(outerSignal.reason);
outerSignal.addEventListener("abort", forward, { once: true });
let firstError;
try {
const running = jobs.map(job =>
job(controller.signal).catch(error => {
if (firstError === undefined) {
firstError = error;
controller.abort(error);
}
throw error;
})
);
const results = await Promise.allSettled(running);
if (outerSignal.aborted) throw outerSignal.reason;
if (firstError !== undefined) throw firstError;
return results.map(result => result.value);
} finally {
outerSignal.removeEventListener("abort", forward);
}
}
// Counts abort listeners currently attached to one signal.
function watchListeners(signal) {
let count = 0;
const add = signal.addEventListener.bind(signal);
const remove = signal.removeEventListener.bind(signal);
signal.addEventListener = (type, fn, options) => {
count += 1;
add(type, fn, options);
};
signal.removeEventListener = (type, fn, options) => {
count -= 1;
remove(type, fn, options);
};
return () => count;
}
const held = deferred();
const user = new AbortController();
const listeners = watchListeners(user.signal);
const outer = runAll(
[
async signal => {
console.log("polite started");
await new Promise((resolve, reject) => {
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
});
},
async () => {
console.log("held started");
await held.promise; // ignores its signal
console.log("held finished");
}
],
user.signal
);
let settled = false;
outer.then(
() => (settled = true),
() => (settled = true)
);
user.abort("user left");
await new Promise(resolve => setTimeout(resolve, 0));
console.log(`settled while held: ${settled}`);
held.resolve();
try {
await outer;
} catch (reason) {
console.log(`rejected with: ${reason}`);
}
console.log(`listeners left on caller's signal: ${listeners()}`);
let starts = 0;
try {
await runAll([async () => starts++], user.signal);
} catch (reason) {
console.log(`already aborted: ${reason}, starts: ${starts}`);
}
}
main();polite started
held started
settled while held: false
held finished
rejected with: user left
listeners left on caller's signal: 0
already aborted: user left, starts: 0throwIfAborted() runs before jobs.map, so the pre-aborted call starts nothing. The forward listener turns the caller's abort into an abort of runAll's own controller; the polite job then rejects, but allSettled still waits for the held job, which is why settled while held is false. Checking outerSignal.aborted before firstError makes the caller's reason win over the polite job's rejection. The finally removes forward on every path, including success: with { once: true } alone, a run that never aborted would leave its listener on the caller's signal, and the count would grow with each call.
Change it and test it
Test a non-aborted operation. For the timer example, change abort to normal completion and verify the listener is removed. Explain why wrapping a never-settling third-party promise does not magically make its underlying work cancellable.
Completion is saved in this browser only. It does not measure mastery.