AbortController: Advanced Asynchronous Task Handling in JS
- Abhishek Kumar
- 03 Jan, 2024
One of the challenges of working with asynchronous operations is how to cancel them when they are no longer needed. For example, you may want to abort a fetch request if the user navigates away from the page, or if the request takes too long to complete. The Fetch API provides a way to do this using the AbortController interface. In this blog post, we will explore the inner workings of AbortController and learn how to use its power to improve the performance and user experience of our web app
Fetch
The JavaScript Fetch API is a powerful and flexible way to make HTTP requests from your web applications. It allows you to customize various aspects of the request and response, such as headers, body, credentials, cache, redirect, and more.
Let’s discuss about aborting a request. To abort a request that is intiallised by fetch we use AbortController’s signal method passing a option in fetch. Lets discuss in more detail with an example.
AbortController
An AbortController is an object that can be used to abort requests to one or more web request. here we will discuss about aborting a request in fetch API.
To create an AbortController, we can use the new AbortController() constructor. This will return an object with two properties:
- signal: This is an property of AbortSignal which provides a way to communicate and control the request.
- abort(): This method aborts the request.
let’s take an example of fetch request and try to abort it before it’s completion
// Create a new AbortController
const controller = new AbortController();
// Get the signal from the controller
const signal = controller.signal;
signal.onabort = ()=> {
console.log("onabort() called");
};
// Make a fetch request with the signal option
fetch('https://reqres.in/api/users?delay=30', {signal})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error("other error occurred", error);
}
});
// Abort the request after 5 seconds
setTimeout(() => {
controller.abort("reason of Aborting");
console.log(signal)
// {aborted: true,
// reason: "reason of Aborting",
// onabort: f}
}, 5000);
In this example, we create an AbortController object and store its signal property in a variable. Then, we pass the signal property to the fetch() method. Further we created a obabort function which will be called after the abortion of request. Next, we call controller.abort() after 5 seconds and finally onabort method was called.
When controller.abort() is called, the fetch() promise will be rejected with an error of type DOMException with name AbortError. The abort event will also be emitted on the signal property.
Usages
Now we know about abortcontroller and how to use it. Let’s discuss some of its usecase.
- Canceling request when user leaves the page
- Canceling requests that are taking too long to respond
- Throttling or debouncing fetch requests
- Handling errors gracefully
- Canceling requests while uploading a larger file
If you are working with fetch requests in JavaScript, I recommend using AbortController to abort requests that are no longer needed. This can help you to improve the performance of your webapp.
If you like this article, don't forget to share it with your friends and colleagues.