How to Cancel Fetch Requests in JavaScript

Adrián Guillén Bermúdez - Jun 30 - - Dev Community

Ever wanted to cancel a fetch request in JavaScript? Discover how the **AbortController **makes it easy to manage and stop async operations. Check out this quick guide to master it in just a few steps!

First, you might wonder when you would need to cancel a fetch request. Here are an examples:

When filtering a list of elements in JavaScript, the data often comes from an API. It’s common to add filtering, pagination, and other features to display the list correctly. However, JavaScript does not guarantee that fetch requests will be resolved in the order they were made.

For instance, if a user applies filters quickly, you might make requests A, B, and C in that order. Ideally, you want to display the results of the latest request (C) last. However, due to the fact that the browser and server work asynchronously, requests might resolve out of order. Request C could be resolved first, followed by A and B, leading to incorrect data being displayed to the user.

In such situations, AbortController **helps by allowing you to **cancel requests A and B, ensuring only the latest request (C) is active. This way, the user sees the expected results.
I’m going to show you step by step an example about how to use AbortController to handle this kind of situation.

First, create an AbortController instance. Retrieve the signal from the controller, which will be used to control the fetch request.

Step 1

Then, use the signal in the fetch request options. Handle the response by logging the data. If an error occurs, check if it's an **AbortError **to know if the request was cancelled using the AbortController. If not, you can handle the error as usual.

Step 2

Finally, when you need to cancel the fetch request, because for example, a user is selecting a new filter you can use controller.abort to cancel the previous request. I’m using a setTimeout in this example for simplicity.

Step 3

This is the complete code example.

Complete Example

If you’ve found this short tutorial helpful, please like this post and share it with your colleagues and friends. Have you previously used the AbortController? Share your thoughts in the comments below!

. . . . . .