throwIfAborted Checks Cancellation Between Steps

Long-running loops cannot be interrupted from outside, so cooperative work calls signal.throwIfAborted() between steps to stop cleanly on abort.

JavascriptResilience

Code

snippet
async function importRows(rows, signal) {
  const done = [];
  for (const row of rows) {
    // Cooperative cancellation: bail between steps, not mid-write
    signal.throwIfAborted();
    done.push(row);
    await Promise.resolve(); // stand-in for the real per-row work
  }
  return done;
}

async function main() {
  const controller = new AbortController();
  const run = importRows([101, 102, 103], controller.signal);

  controller.abort(); // default reason is an AbortError DOMException

  try {
    const done = await run;
    console.log("imported all", done.length, "rows");
  } catch (error) {
    console.log("stopped after", error.name, "-", error.message);
    console.log("signal.aborted =", controller.signal.aborted);
  }
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

stopped after AbortError - This operation was aborted
signal.aborted = true

Following each operation

Everything happens inside the functions importRows and main.

for (const row of rows) is the loop that carries the per-item work. The async parts await their results, which keeps ordering predictable.

Caveats

  • Everything it calls is documented as part of the language core.

Using it

Signature: async function importRows(rows, signal)

The run prints imported all, stopped after, signal.aborted = — each prefix names the step that produced it.

The sequence importRows lives in main; running the file triggers it.

Key statements

await Promise.resolve(); // stand-in for the real per-row work
}
const controller = new AbortController();
const done = await run;

Interactive Tools for This Topic

FAQ

What does throwIfAborted Checks Cancellation Between Steps print when run?
Execute the whole file; each printed line is prefixed with a label like `stopped after`, `signal.aborted =`.