Sub topic 9
Cancellation Checkpoints in Async Loops
This chapter assumes you are comfortable with async/await, for...of loops, and try/catch. It also assumes you know the signal.aborted and signal.reason properties and the optional { signal } options convention from earlier chapters.
Earlier chapters showed how to cancel a single operation, such as one timer, by listening for the abort event. Many real functions are loops instead: they process a list of items, page through results, or retry a step until it succeeds. Each iteration might await something, and some of that work may not accept a signal at all. Cancelling a loop like this takes a different tool, which is the cancellation checkpoint.
Why the abort event alone does not stop a loop
JavaScript runs your code to completion. When the caller runs controller.abort(), the signal changes state and its abort listeners run. Your loop, however, keeps going. Nothing interrupts the for statement, and no exception appears inside it unless your code goes looking for one.
So the loop has to ask, at chosen points, "has the caller cancelled me?" Each of those points is a checkpoint. If the answer is yes, the loop stops and the function rejects with the abort reason, just as a built-in API would.
throwIfAborted() as a one-line checkpoint
signal.throwIfAborted() does nothing when the signal is not aborted. When it is aborted, it throws signal.reason. That is the same value you would reject with by hand, so you can write the checkpoint in one line:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function processAll(items, { signal } = {}) {
const results = [];
for (const item of items) {
signal?.throwIfAborted();
await sleep(100); // stands in for a step that does not accept a signal
results.push(item * 2);
}
return results;
}
const controller = new AbortController();
setTimeout(() => controller.abort(), 250);
processAll([1, 2, 3, 4, 5], { signal: controller.signal })
.then((results) => console.log('done', results))
.catch((err) => console.log('stopped:', err.name)); // "stopped: AbortError"Because the function is async, the thrown reason becomes a rejection of the returned promise. You do not need to call reject yourself. The optional chaining (signal?.) keeps the signal optional, following the convention from the API design chapter.
Compare this with if (signal?.aborted) throw signal.reason;. The two behave the same. throwIfAborted() is shorter, and it makes it harder to throw the wrong value by mistake. It exists in all current browsers and in Node.js 17.3 and later.
How long cancellation takes
Trace the example on a timeline. Checkpoints run at 0 ms, 100 ms, and 200 ms, and each passes. The third step starts at 200 ms and finishes at 300 ms. The abort happens at 250 ms, in the middle of that step, so nothing notices it until the checkpoint at 300 ms throws.
A checkpoint loop therefore stops within one step of the abort, not immediately. The worst-case delay is the length of the longest step between two checkpoints. If that is too long, you have two choices. You can add more checkpoints, or you can pass the signal into the step itself so the step can stop partway through. The next chapter covers the second choice for fetch and nested calls.
Where to put checkpoints
Two places matter most: at the start of each iteration, and right after each await whose work ignores the signal. The check after an await stops the loop from acting on a result the caller no longer wants, such as writing it to storage or updating the UI.
| Placement | What it prevents | When to use it |
|---|---|---|
| Top of each iteration | Starting new work after cancel | Always |
| Right after an `await` | Acting on a stale result | When the next lines have side effects |
| Every N iterations in a sync section | Blocking forever in CPU-heavy code | Long computations (see below) |
| Inside a retry or backoff loop | Retrying after cancel | Any retry loop |
The check at the top of the first iteration also covers the case of a signal that was already aborted. An empty items array would skip that check, though. If the function must reject on an already-aborted signal even with no input, put one signal?.throwIfAborted() before the loop, as the fail-fast chapter recommends.
Checkpoints cost almost nothing, since each one reads a property. Don't worry about having too many in async code. The cost to watch for is in tight synchronous loops, which the next section covers.
CPU-heavy loops must yield
A purely synchronous loop can never be cancelled by a checkpoint alone. While it runs, the event loop cannot run the timer, click handler, or message that would call abort(). The signal stays un-aborted until the loop ends, so every check passes.
The fix is to hand control back to the event loop now and then, and to check after each pause:
const yieldToEventLoop = () => new Promise((resolve) => setTimeout(resolve, 0));
async function sumSquares(n, { signal } = {}) {
let total = 0;
for (let i = 0; i < n; i++) {
if (i % 1_000_000 === 0) {
await yieldToEventLoop();
signal?.throwIfAborted();
}
total += i * i;
}
return total;
}
const controller = new AbortController();
setTimeout(() => controller.abort(), 20);
sumSquares(1e10, { signal: controller.signal })
.then((total) => console.log(total))
.catch((err) => console.log('stopped:', err.name)); // "stopped: AbortError"Choose the batch size (here one million iterations) so that each batch takes a few milliseconds. If batches are too small, the loop spends its time yielding. If they are too large, cancellation and the rest of the page both lag.
Cleaning up when a checkpoint throws
A checkpoint throws in the middle of your function, so any resource the loop opened has to be closed on that path too. Use finally so cleanup runs after success, after a real error, and after a cancellation:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function exportRows(rows, { signal } = {}) {
const lines = [];
console.log('opening export');
try {
for (const row of rows) {
signal?.throwIfAborted();
await sleep(50);
lines.push(JSON.stringify(row));
}
return lines.join('\n');
} finally {
console.log(`closing export after ${lines.length} rows`);
}
}
const controller = new AbortController();
setTimeout(() => controller.abort(), 120);
exportRows([{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }], { signal: controller.signal })
.catch((err) => console.log('stopped:', err.name));The rows already processed are thrown away along with the rejection. That matches built-in APIs, which reject rather than resolve with partial data. If callers really need partial progress, report it through a separate callback such as onProgress. Don't resolve early with a half-filled array.
Common errors
Swallowing the abort inside the loop
A per-item try/catch meant to skip bad items will also catch the checkpoint's exception and keep looping:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function processLenient(items, { signal } = {}) {
const results = [];
for (const item of items) {
try {
signal?.throwIfAborted();
await sleep(50);
if (item < 0) throw new Error(`bad item ${item}`);
results.push(item);
} catch (err) {
if (signal?.aborted) throw err; // never swallow cancellation
console.warn('skipping:', err.message);
}
}
return results;
}Test signal.aborted here rather than err.name === 'AbortError'. If the caller passed a custom reason or a timeout reason, the name will be something else, but the signal will still say it was aborted.
Returning instead of throwing
Writing if (signal.aborted) return results; makes the promise resolve, so the caller cannot tell "finished" from "cancelled". Reject with signal.reason so callers can handle cancellation in one consistent way.
Using forEach with an async callback
items.forEach(async (item) => { ... }) starts every callback at once and ignores their promises. A checkpoint inside the callback rejects that one callback's promise, which nobody awaits, so you get an unhandled rejection and the other callbacks keep running. Use for...of for sequential work. For parallel work, use Promise.all and put a checkpoint inside each task.
Exercise
A loop awaits a 2-second step that does not accept a signal, with a single throwIfAborted() at the top of each iteration. The caller aborts 0.5 seconds into a step. How long until the promise rejects, and name two ways to shorten that delay.
Show answer
About 1.5 seconds. The current step finishes at the 2-second mark, and the next top-of-iteration checkpoint then throws. To shorten the delay, pass the signal into the step so it can stop partway through, or split the step into smaller awaited pieces with a checkpoint after each one. A checkpoint right after the await would not reduce the delay, but it would stop the loop from acting on the stale result.
Exercise
This code never cancels, even though a timer calls controller.abort() after 10 ms: async function count(n, { signal }) { for (let i = 0; i < n; i++) { if (i % 1000 === 0) { await Promise.resolve(); signal.throwIfAborted(); } } }. Why, and what is the fix?
Show answer
await Promise.resolve() yields only to the microtask queue, and microtasks run before timers. The setTimeout callback that calls abort() never runs while the loop is going, so the signal is never aborted when checked. Yield with a macrotask instead, for example await new Promise((r) => setTimeout(r, 0)) or scheduler.yield(), and then call throwIfAborted().
Exercise
Why should a per-item catch block rethrow when signal.aborted is true instead of when err.name === 'AbortError'?
Show answer
The signal's reason can be any value: a TimeoutError from AbortSignal.timeout(), or a custom Error passed to abort(). Checking the name would swallow those reasons and keep the loop running. Checking signal.aborted catches every kind of cancellation, whatever its reason.