liveBook · Manning

AbortSignal

As explained in Vanilla Web

A web-platform interface that communicates cancellation of an asynchronous operation.

A route change can make an in-flight request irrelevant. An AbortSignal communicates that cancellation to an asynchronous operation. Pass it through the functions that start work, rather than treating cancellation as an unrelated router or component concern. section 10.3.3 section 12.5

event.intercept({
  async handler() {
    const response = await fetch(`/api/products/${id}`, {
      signal: event.signal
    });

    if (!response.ok) throw new Error("Failed to load product");

    const product = await response.json();
    renderProductPage(product);
  }
});

Passing event.signal to fetch() ties the product request to its navigation. If another navigation supersedes it, the request is aborted automatically. section 10.3.3

Treat an expected abort differently from a failed request. An uncaught aborted fetch throws an error named AbortError and causes a navigateerror event. Catch that error in the route handler and return silently; show an error for other failures. section 10.3.3

The same signal pattern applies beyond route requests:

  • Pass a signal to the original fetch() for a streaming response; aborting the request also stops reading its body. section 12.1.7
  • Pass a component-owned controller’s signal to addEventListener() calls. A component can set listeners up on connection and abort them together on disconnection. section 13.2.7

Shared requests need a cancellation policy

A cache that stores an in-flight Promise lets two callers share one request. If the first caller supplied its signal and aborts, both callers awaiting that Promise fail. Independent cancellation requires reference counting around the underlying AbortController; do not assume a shared request gives each caller its own cancellation state. section 12.3

How Vanilla Web covers it

How deep it goes
Shows signal propagation, abort handling, and shared-request consequences; defers reference-counted independent cancellation.
Examples
Uses a product-route fetch, component listener cleanup, streaming fetch, and an in-flight product cache.
What you can do after
Apply it via native web APIs to cancel superseded fetches, handle expected aborts, and identify shared-request cancellation risks.
How it connects
Connects the Navigation API, fetch(), AbortController, streaming responses, EventTarget, and Promise-based caching.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Vanilla Web. The section links point to the parts of the book it draws on.