Learning on Web Dev Open is free for all.

Systems Thinking > One thread, several queuesCancellation is a design decision
Phase 03One thread, several queues143 of 434

Cancellation is a design decision

A promise cannot be cancelled. AbortController is how you tell the work to stop, and threading a signal through is a design problem, not a plumbing one.

Concept14 minAI pair

A promise is a notification that something finished. It has no handle on the thing that is doing the work, so there is nothing there to cancel. AbortController splits the concern properly: the controller is held by whoever decides to stop, the signal is passed to whoever is doing the work, and the two never need to know about each other.

fetch takes a signal and rejects with an AbortError, which is a DOMException and not an Error subclass you can instanceof cheaply. Check err.name === "AbortError", and do not report it as a failure, because a cancellation you asked for is not an error the user needs to see. Your own long-running functions should take a signal too, check signal.aborted between chunks of work, and listen for the abort event when they are waiting on something.

Aborting is different from ignoring. Ignoring a stale result, checking on arrival that the request is still the current one, fixes the display bug and still pays for the network. Aborting fixes the display bug and frees the connection. Do both: abort what you can reach, and keep the staleness check for the cases where the response was already in flight.

You should now be able to

  • Wire an AbortSignal through fetch and your own async functions
  • Distinguish aborting the work from ignoring the result
Ask the community

Loading…