Node.js theorytheory 0/50 · 0%
Advanced · hard

41. AbortController and cancellation

Cancelling fetch requests and long-running operations.

`AbortController` provides a standard way to cancel an in-progress async operation — most commonly a `fetch` call that's taking too long, but also usable for any custom async function that checks `signal.aborted`.

js
async function fetchWithTimeout(url, ms) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), ms);
  try {
    const res = await fetch(url, { signal: controller.signal });
    return await res.json();
  } finally {
    clearTimeout(timer);
  }
}

Without a timeout mechanism like this, a single slow or hung upstream RPC endpoint can leave requests (and their resources) pending indefinitely — a real risk when your service depends on external nodes you don't control.

Check your understanding

  1. 1. What does calling controller.abort() do to a fetch using its signal?

  2. 2. Why is a request timeout important when calling external RPC endpoints?

  3. 3. What should you check inside a custom cancellable async function?