Aborting Requests with AbortController
You'll learn how to cancel fetch requests mid-flight to avoid wasted work and handle cleanup when requests are no longer needed.
Sometimes you need to stop a network request before it completes—maybe the user navigated away, clicked a different search result, or closed a modal. Without cancellation, the browser keeps processing responses you no longer care about, wasting bandwidth and potentially causing bugs.
How AbortController Works
Think of AbortController like a remote control's stop button for your fetch requests. You create an AbortController object, pass its signal property to fetch, and later call controller.abort() to cancel.
Basic Pattern
const controller = new AbortController();
fetch('https://api.example.com/data', {
signal: controller.signal
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request was canceled');
} else {
console.error('Request failed:', error);
}
});
// Cancel the request
controller.abort();
Real-World Use Case
let controller = null;
function searchUsers(query) {
// Cancel previous search if still running
if (controller) {
controller.abort();
}
// Start new search
controller = new AbortController();
fetch(`/api/search?q=${query}`, {
signal: controller.signal
})
.then(response => response.json())
.then(results => displayResults(results))
.catch(error => {
if (error.name !== 'AbortError') {
console.error('Search failed:', error);
}
});
}
When abort() is called, the fetch promise rejects with an AbortError. You can check error.name === 'AbortError' to distinguish cancellations from real failures.
Key Takeaway: Use AbortController and its signal property to cancel fetch requests, preventing wasted resources and handling cleanup when requests become obsolete—essential for responsive, user-driven interfaces.