← Concepts

阅读中文版本

Promise and Task Cancellation

Cancellation is cooperative: a signal tells the operation to stop, and the operation must check the signal at safe points — otherwise aborts leak resources and race completion paths.

concurrency

Definition

Cancellation in async systems is a request, not an interruption: a token or signal is raised, and well-behaved operations poll or subscribe, then unwind cleanly at cancellation-safe points. Cooperative cancellation preserves invariants; forced cancellation via API removal risks inconsistent state. Design covers propagation, composition with timeouts, and finalization on cancel.

Context and scope

Implemented as AbortController in JS, CancellationToken in .NET, kotlinx.coroutines cancellation, and Go context. Applied to request handlers, fan-out queries, and long jobs.

Common misconceptions

  • Dropping the reference cancels the promise — detached promises keep running to completion, consuming CPU and network regardless
  • Cancellation throws like an error — cancellation is control flow, not failure; treating it as rejection mixes user navigation with server faults
  • Timeout wrappers cancel the underlying work — many timeout helpers race a timer without signaling the operation, which keeps running invisibly

Anti-patterns

  • Racing a timeout against fetch without passing the signal, leaving the request running after timeout
  • Catching cancellation exceptions in generic error handlers and retrying operations the user already abandoned
  • Registering cancel listeners but never checking the token inside compute-heavy loops

Related concepts

Related examples

Authoritative source

https://developer.mozilla.org/en-US/docs/Web/API/AbortController

What it is

Async work needs an off switch that composes: a request abandoned by the user, a fan-out superseded by the first success, a deadline exceeded. Cancellation tokens model the switch; the operation cooperates by checking it and unwinding deterministically.

How it works

A controller raises the signal; the operation observes it — awaited primitives reject with a cancellation-specific error, loops check at iteration boundaries, and cleanup runs in finally. Composition rules: child tokens cancel with parents, links combine signals, and deadlines are tokens driven by timers.

When to design

Any operation that can outlive its usefulness: HTTP requests, database queries, batch jobs, and fan-out scopes. Expose cancellation in your SDK signatures so callers can pass tokens through every layer.

Pitfalls

Cancellation-aware libraries must release locks, connections, and partial writes on cancel — test these paths explicitly. Mixing cancellation errors into retry logic causes ghost retries of work the user canceled. Callback leaks from cancel listeners on long-lived controllers are a slow memory leak.