JAVASCRIPT
Handling Abortable API Requests with `AbortController`
Learn to cancel pending Fetch API requests in JavaScript using `AbortController` to improve performance and user experience in dynamic web applications.
// Function to fetch data that can be aborted
async function fetchData(url, signal) {
try {
const response = await fetch(url, { signal }); // Pass the signal to fetch
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('Data fetched successfully:', data);
return data;
} catch (error) {
if (error.name === 'AbortError') {
console.log('Fetch aborted!');
// Handle cleanup or specific UI updates for aborted requests
} else {
console.error('Fetch error:', error);
}
throw error; // Re-throw if it's not an AbortError
}
}
// Example usage in a component or event handler
let currentAbortController = null;
async function handleSearchInput(query) {
// If there's an ongoing request, abort it
if (currentAbortController) {
currentAbortController.abort();
console.log('Previous request aborted.');
}
// Create a new AbortController for the current request
currentAbortController = new AbortController();
const signal = currentAbortController.signal;
try {
console.log(`Fetching data for query: "${query}"...`);
const data = await fetchData(`https://api.example.com/search?q=${query}`, signal);
console.log('Search results:', data);
// Process data
} catch (error) {
// Only log/handle non-abort errors here
if (error.name !== 'AbortError') {
console.error('Search failed:', error);
}
} finally {
// Clear the controller reference once the request is settled (or aborted)
if (currentAbortController && !signal.aborted) { // Only if not already aborted by a new call
currentAbortController = null;
}
}
}
// Simulate user typing:
// Call handleSearchInput with different queries
handleSearchInput('apple');
setTimeout(() => handleSearchInput('banana'), 200); // This will abort 'apple'
setTimeout(() => handleSearchInput('orange'), 500); // This will abort 'banana'
setTimeout(() => handleSearchInput('grape'), 2000); // This will likely complete
How it works: This JavaScript snippet demonstrates how to make API requests abortable using the `AbortController` Web API. When a new search query or action is initiated, any previously pending request can be cancelled immediately, preventing unnecessary network traffic and stale data from updating the UI. This is particularly useful for features like type-ahead search or dynamic components where users might rapidly trigger multiple data fetches, significantly improving responsiveness and resource management.