I. Introduction

AbortController is a built-in JavaScript object that allows you to abort one or more DOM requests as and when desired. It is particularly useful for managing asynchronous operations, such as network requests, where you may want to cancel an operation if it is no longer needed.

II. Using AbortController

The most common use case for AbortController is with the Fetch API. You can use it to cancel a fetch request if it takes too long or if you no longer need the response.

const [userCancelledController, setUserCancelledController] = useState<AbortController>()

async function makeApiCall() {
  const controller = new AbortController
  setUserCancelledController(controller) // so we can call .abort() on it elsewhere

  const timeoutSignal = AbortSignal.timeout(5000);

  window.fetch('https://example.com/api', {
    signal: AbortSignal.any(
    [
      timeoutSignal, // after 5000 ms
      controller.signal // or if user clicks cancel button
    ]
  )}).catch(console.error)
}

return <>
  <button onClick={() => userCancelledController?.abort()}>Manual abort!</button>

  <button onClick={makeApiCall}>
    Fetch with automatic timeout abort
  </button>
</>

III. Handling Abort Errors

When you abort a fetch request, it throws an AbortError. You can catch this error in the .catch() block of your promise chain. This allows you to handle the cancellation gracefully without crashing your application.

IV. Conclusion

AbortController is a powerful tool for managing asynchronous operations in JavaScript. By using it with the Fetch API, you can easily cancel requests that are no longer needed, improving the performance and responsiveness of your applications. Remember to handle the AbortError to ensure a smooth user experience.