JAVASCRIPT
Aborting Pending Fetch Requests with AbortController
Efficiently cancel ongoing network requests in JavaScript using AbortController. Prevent race conditions and optimize resource usage in SPAs.
let currentController = null;
async function searchData(query) {
// Abort any previous pending request
if (currentController) {
currentController.abort();
}
currentController = new AbortController();
const signal = currentController.signal;
try {
const response = await fetch(`https://api.example.com/search?q=${query}`, { signal });
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log('Search Results:', data);
// Process data here
} catch (error) {
if (error.name === 'AbortError') {
console.log('Fetch request was aborted.');
} else {
console.error('Fetch error:', error);
}
} finally {
currentController = null; // Clear controller once request is finished or aborted
}
}
// Example usage:
// User types 'apple' then quickly types 'banana'
// searchData('apple');
// searchData('banana'); // This will abort the 'apple' request and start a new one
How it works: This JavaScript snippet shows how to use the `AbortController` API to cancel pending `fetch` requests. This is particularly useful in scenarios like search bars or rapid UI interactions where new requests might invalidate older, still-pending ones. By aborting previous requests, you prevent race conditions, reduce unnecessary network traffic, and ensure that only the most recent data updates the UI, improving application responsiveness and efficiency.