JAVASCRIPT
Canceling Pending API Requests with AbortController in JavaScript
Improve performance and user experience by learning to cancel unwanted or stale API requests using the AbortController with the Fetch API.
function makeCancellableRequest(url, options = {}) {
const controller = new AbortController();
const signal = controller.signal;
const promise = fetch(url, { ...options, signal })
.then(response => {
if (!response.ok) {
return response.json().then(errorData => {
throw new Error(errorData.message || `HTTP error! Status: ${response.status}`);
});
}
return response.json();
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('Fetch aborted:', url);
// Do not re-throw if it's an intentional abort
} else {
console.error('Fetch error:', error);
throw error;
}
});
return { promise, cancel: () => controller.abort() };
}
// Example Usage in a component or event handler
/*
let currentRequest = null;
async function fetchData() {
// Cancel previous request if it exists
if (currentRequest) {
currentRequest.cancel();
}
const { promise, cancel } = makeCancellableRequest('https://api.example.com/search?q=query');
currentRequest = { promise, cancel }; // Store the controller for potential cancellation
try {
const data = await promise;
console.log('Data:', data);
currentRequest = null; // Clear request once completed
} catch (err) {
if (err.name !== 'AbortError') { // Only log/handle actual errors, not cancellations
console.error('Error fetching data:', err);
}
}
}
// Simulate fetching and then cancelling
// fetchData();
// setTimeout(() => {
// if (currentRequest) {
// console.log('Cancelling request after 1 second...');
// currentRequest.cancel();
// currentRequest = null;
// }
// }, 1000);
*/
How it works: This snippet shows how to use `AbortController` to cancel ongoing `fetch` requests. This is particularly useful in scenarios like search bars (to cancel previous requests as the user types), or when a component unmounts before an API call completes, preventing state updates on unmounted components and unnecessary network traffic. The function returns both the promise and a `cancel` method.