throwIfAborted Cancels Work Cooperatively

Call signal.throwIfAborted() at stage boundaries so a cancelled pipeline stops between steps and surfaces rejection as AbortError, not wasted computation.

TypescriptResilience

Code

typescriptsnippet
31 lines
const controller = new AbortController();

async function step(name: string, ms: number, signal: AbortSignal): Promise<string> {
  await new Promise((resolve) => setTimeout(resolve, ms));
  // 每个阶段结束点主动检查:throwIfAborted 抛出 signal.reason
  signal.throwIfAborted();
  return `done: ${name}`;
}

async function pipeline(signal: AbortSignal): Promise<string[]> {
  const results: string[] = [];
  for (const name of ["fetch", "parse", "render"]) {
    results.push(await step(name, 30, signal));
    console.log(results.at(-1));
    if (results.length === 1) {
      // 第一步完成后用户取消:后续阶段在检查点退出,不再白跑
      controller.abort();
    }
  }
  return results;
}

const run = pipeline(controller.signal).catch((error: unknown) => {
  // 未传 reason 的 abort() 抛出 AbortError,与业务错误区分
  const aborted = error instanceof Error && error.name === "AbortError";
  console.log(`aborted: ${aborted}`);
});

await run;
console.log("pipeline settled");

Output

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

done: fetch
aborted: true
pipeline settled

Inside the snippet

Two functions carry the flow: step sleeps for its stage and then checks the signal, and pipeline walks the three stages one by one.

The for loop over ["fetch", "parse", "render"] runs each stage through step; after the first stage completes, controller.abort() fires, so the next checkpoint throws. The AbortError raised by step’s next throwIfAborted() propagates out of pipeline and is caught by the .catch, which logs aborted: true.

What to watch for

  • Only runtime built-ins appear — AbortController, signal.throwIfAborted(), setTimeout, Promise — nothing to install.
  • Runs as-is in Node and the browser alike — AbortController and signal.throwIfAborted() are built into both; the "fetch" in the stage list is only a stage name, not the fetch API.

Putting it to use

step’s shape is the contract to copy: async function step(name: string, ms: number, signal: AbortSignal) — a unit of work that always ends at signal.throwIfAborted().

One run prints three lines: done: fetch from stage one, then aborted: true from the catch handler, then pipeline settled.

Core lines

await new Promise((resolve) => setTimeout(resolve, ms));
const run = pipeline(controller.signal).catch((error: unknown) => {
// 未传 reason 的 abort() 抛出 AbortError,与业务错误区分
const aborted = error instanceof Error && error.name === "AbortError";
console.log(`aborted: ${aborted}`);
});
async function pipeline(signal: AbortSignal): Promise<string[]> {
const results: string[] = [];
for (const name of ["fetch", "parse", "render"]) {
results.push(await step(name, 30, signal));
console.log(results.at(-1));
if (results.length === 1) {
// 第一步完成后用户取消:后续阶段在检查点退出,不再白跑
controller.abort();
}
}
return results;
}

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `step`, `pipeline` at load time.