Published on

Cancel API Requests in JavaScript using AbortController

Authors

These days, pretty much all web apps heavily rely on API-based approach to perform an action. However, sometimes we might need to cancel these requests before they are complete. That's where AbortController comes in.

AbortController allows you to easily cancel API requests (like with fetch) or any other asynchronous tasks.

How does it work?

AbortController is a build-in JavaScript API with a simple API (controller and signal)

controller provides the ability to abort the signal, while the signal is an object that is passed to the asynchronous task, like a fetch API call.

How to use?

const controller = new AbortController();

const signal = controller.signal;
fetch('https://jsonplaceholder.typicode.com/posts/1?_delay=5000', { signal })
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));


// Let's assume that we want to cancel the request while that API request is being processed
controller.abort();

What's the benefits?

AbortController helps to cancel unwanted requests that are no longer needed, which can improve performance and reduce unwanted bandwidth consumption.

In conclusion, using AbortController for canceling requests is a simple and effective way to improve performance and reduce unwanted bandwidth consumption in web apps.

Happy cancelling requests!