JavaScript: AbortController

AbortController lets you cancel a fetch request or other supported asynchronous operation that is no longer needed.

What you will learn

Minimal example

const controller = new AbortController();
const request = fetch("data.json", { signal: controller.signal })
  .then(response => {
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json();
  })
  .catch(error => {
    if (error.name === "AbortError") {
      console.log("The request was cancelled.");
      return;
    }
    console.error("The request failed:", error);
  });

controller.abort();

Calling abort() causes the request to reject with an AbortError. Keep a separate branch for cancellation so it is not reported as an unexpected server or network failure.

Important points