JAVASCRIPT
Cancelling In-Flight API Requests with AbortController
Learn how to effectively cancel pending `fetch` API requests using `AbortController` in JavaScript, preventing race conditions and optimizing resource usage in dynamic web applications.
function makeCancellableRequest(url, options = {}) {
const controller = new AbortController();
const signal = controller.signal;
const promise = fetch(url, { ...options, signal })
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('Fetch request was aborted.');
// Re-throw or handle silently depending on context
throw new Error('Request aborted by user/system.');
}
throw error;
});
return { promise, abort: () => controller.abort() };
}
// Example Usage:
// let currentRequest = null;
// async function fetchData(query) {
// // If there's an ongoing request, abort it
// if (currentRequest) {
// currentRequest.abort();
// console.log('Previous request aborted.');
// }
// try {
// currentRequest = makeCancellableRequest(`https://api.example.com/search?q=${query}`, { method: 'GET' });
// const data = await currentRequest.promise;
// console.log('Search results:', data);
// currentRequest = null; // Request completed, clear reference
// } catch (error) {
// if (error.message !== 'Request aborted by user/system.') {
// console.error('Failed to fetch data:', error);
// }
// currentRequest = null; // Request failed or aborted, clear reference
// }
// }
// // Simulate rapid typing:
// // fetchData('apple');
// // setTimeout(() => fetchData('apples'), 100); // Aborts 'apple'
// // setTimeout(() => fetchData('applesauce'), 200); // Aborts 'apples')
How it works: This snippet demonstrates how to cancel a pending `fetch` API request using the `AbortController` API. It wraps a `fetch` call, associating it with an `AbortSignal`. The returned object includes both the `promise` for the request and an `abort` function. Calling `abort()` on the controller will stop the in-flight request, preventing it from consuming resources or causing unwanted side effects, which is crucial for scenarios like user navigation or fast-typing search inputs.