Changed Your Mind? Cancel It.
One limitation of Promises is that they cannot be cancelled once started. But for network requests, the AbortController API makes cancellation possible.
How It Works
const controller = new AbortController();
const signal = controller.signal; // A special "abort signal" object
// Attach the signal to the fetch request
fetch('/api/search?q=hello', { signal })
.then(response => response.json())
.then(data => displayResults(data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('Request was cancelled by the user.');
} else {
console.error('Network error:', err);
}
});
// Cancel the request after 5 seconds (e.g., if user navigated away)
setTimeout(() => controller.abort(), 5000);
A Real-World Use Case: Live Search
let searchController;
searchInput.addEventListener('input', async function() {
// Cancel the previous search if the user is still typing
if (searchController) searchController.abort();
searchController = new AbortController();
try {
const response = await fetch('/search?q=' + this.value, {
signal: searchController.signal
});
displayResults(await response.json());
} catch (err) {
if (err.name !== 'AbortError') showError(err);
}
});
Important
AbortController is essential for interfaces where users can quickly switch between tabs, filters, or search queries. Cancel stale requests to save bandwidth and avoid showing outdated results.