How do you abort a web request using AbortController in JavaScript?
The AbortController
API in JavaScript provides a way to abort web requests, such as fetch
or other asynchronous tasks, when they are no longer needed. This is particularly useful for scenarios like canceling requests when navigating away from a page or stopping redundant API calls.
Basic Syntax of AbortController
The AbortController
API works by creating a controller object that can send a signal to abort associated requests.
Steps to Use AbortController
- Create an instance of
AbortController
. - Pass the controller's
signal
property to thefetch
or other request function. - Call
abort()
on the controller to cancel the request.
Example: Using AbortController with Fetch
// Create an instance of AbortController
const controller = new AbortController();
const signal = controller.signal;
// Start a fetch request with the signal
fetch('https://api.example.com/data', { signal })
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
console.log('Fetched data:', data);
})
.catch((error) => {
if (error.name === 'AbortError') {
console.log('Fetch request was aborted.');
} else {
console.error('Fetch error:', error);
}
});
// Abort the fetch request after 2 seconds
setTimeout(() => {
controller.abort();
console.log('Request aborted');
}, 2000);
Output
- If the request completes within 2 seconds, the data is logged.
- If it exceeds 2 seconds, the request is aborted, and the
AbortError
is handled.
Advanced Example: Aborting Multiple Requests
The same AbortController
instance can be used to manage multiple requests simultaneously.
const controller = new AbortController();
const signal = controller.signal;
// Start multiple fetch requests
Promise.all([
fetch('https://api.example.com/data1', { signal }),
fetch('https://api.example.com/data2', { signal }),
])
.then((responses) => Promise.all(responses.map((res) => res.json())))
.then((data) => {
console.log('Fetched data:', data);
})
.catch((error) => {
if (error.name === 'AbortError') {
console.log('One or more requests were aborted.');
} else {
console.error('Fetch error:', error);
}
});
// Abort all requests after 1 second
setTimeout(() => {
controller.abort();
console.log('All requests aborted');
}, 1000);
Benefits of Using AbortController
- Resource Management: Prevents unnecessary resource consumption for requests no longer needed.
- Improved UX: Enables canceling redundant or stale requests in real-time applications.
- Error Handling: Clearly distinguishes between aborted requests and other types of errors.
Limitations
- Limited Browser Support: Older browsers may not support
AbortController
. Always check compatibility or use a polyfill. - Not Supported by All APIs: While widely supported by
fetch
, not all web APIs are compatible withAbortController
.