What is the purpose of the AbortController when making fetch requests?
const controller = new AbortController();
const { signal } = controller;
fetch('/api/data', { signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
} else {
console.error('Other error:', err);
}
});
// Abort the fetch after 5 seconds
setTimeout(() => controller.abort(), 5000);
AbortController provides a way to cancel one or more fetch requests on demand. This is useful for: 1) Canceling requests when they're no longer needed (e.g., user navigates away), 2) Implementing timeout logic for requests, 3) Canceling multiple requests simultaneously using the same controller, 4) Cleaning up resources and preventing unnecessary network traffic. The signal from AbortController can be passed to fetch options, and calling abort() will cancel the request and reject the promise with an AbortError.