Taming fetch: Reliable Request Cancellation by Button and Timeout with AbortSignal.any()Brief · digest for October 15
Brief≈ 1 min

Taming fetch: Reliable Request Cancellation by Button and Timeout with AbortSignal.any()

Remember how much boilerplate it used to take to cancel a network request on both a user click and a timeout? You had to create a controller, attach timer listeners, and manually clean up subscriptions to avoid memory leaks.

The native AbortSignal.any() method combines any number of signals into one:

// Combine manual button cancellation and a 5-second timeout
const userCancel = new AbortController();
const signal = AbortSignal.any([userCancel.signal, AbortSignal.timeout(5000)]);

It also preserves the exact cancellation reason, which simplifies handling UX scenarios in the UI:

try {
  const res = await fetch('/api/data', { signal });
  const data = await res.json();
} catch (err) {
  if (err.name === 'AbortError') console.info('Request canceled by user');
  else if (err.name === 'TimeoutError') console.warn('Request timed out');
}

Linking through weak references ensures the garbage collector cleans everything up properly without manual timer teardown.

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2