Sub topic 9
Cancellation Checkpoints in Async Loops
This chapter assumes you know async/await, for...of loops, and try/catch. It also assumes you have read the earlier chapters on signal.aborted, signal.reason, and the { signal } options convention.
The problem with long loops
A function that runs many async steps in a row can keep going long after the caller has given up. Suppose a loop processes 1,000 items and the user cancels at item 3. Unless the loop checks the signal, it runs the other 997 steps anyway. The caller has already moved on, so that work just wastes CPU, network, and battery.
You fix this with a cancellation checkpoint. A checkpoint is a point in your code where you ask "has the signal aborted?" and stop if the answer is yes.
throwIfAborted()
signal.throwIfAborted() does the check in a single call. If the signal has aborted, it throws signal.reason. If not, it does nothing. Because it throws, the error leaves your loop and rejects the promise your async function returned. You do not have to write any extra code for that.
async function sumSlowly(numbers, { signal } = {}) {
let total = 0;
for (const n of numbers) {
signal?.throwIfAborted();
await new Promise((resolve) => setTimeout(resolve, 100));
total += n;
}
return total;
}
const controller = new AbortController();
sumSlowly([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], { signal: controller.signal })
.then((total) => console.log('total:', total))
.catch((err) => console.log('stopped:', err.name)); // "stopped: AbortError"
setTimeout(() => controller.abort(), 350);The optional chaining in signal?.throwIfAborted() keeps the signal optional, so callers who never cancel can skip it.
Where to put checkpoints
A checkpoint only runs when your code reaches it. In the example above, the abort happens at 350 ms, during the fourth wait. That wait still finishes at 400 ms, and the checkpoint at the top of the fifth iteration is what throws. So the time between checkpoints sets how quickly your function responds to a cancel.
| Placement | Why |
|---|---|
| Top of each iteration | Stops before starting new work |
| Right after an `await` | Avoids acting on a result the caller no longer wants |
| Before expensive synchronous work | Skips CPU-heavy steps that cannot be interrupted |
A checkpoint cannot interrupt an await while it is still waiting. To stop the step itself, the awaited operation must accept the signal too. For example, fetch(url, { signal }) or the cancellable delay() from earlier both stop as soon as the signal aborts. The next chapter covers passing the signal down to calls like these.
A common mistake
Checking signal.aborted and then using break exits the loop, but your function then returns a partial result as if it succeeded. The caller cannot tell that the work was cancelled. Throwing the reason keeps the behavior the same as built-in APIs, which reject when they are aborted.
Exercise
A loop does for (const file of files) { const data = await readFile(file); signal?.throwIfAborted(); await upload(data); }. The caller aborts while readFile is running. What happens, and why is this checkpoint placement good?
Show answer
readFile finishes, because the checkpoint cannot interrupt it. Then throwIfAborted() throws signal.reason before upload starts, and the function's promise rejects. Putting the checkpoint right after the await means the code never uploads data the caller no longer wants.
Exercise
Why is if (signal?.aborted) break; a worse checkpoint than signal?.throwIfAborted();?
Show answer
break makes the function resolve normally, often with partial results, so the caller cannot tell the work was cancelled. throwIfAborted() rejects with signal.reason, which matches how platform APIs behave and lets the caller handle the cancellation.