AbortController is a built-in JavaScript mechanism for cancelling asynchronous operations. It allows creating a cancellation signal that can be passed to asynchronous operations (fetch, setTimeout, etc.) to interrupt their execution. This is especially useful for cancelling HTTP requests, timers and other long-running operations.
Main components:
AbortController is a standard API in JavaScript designed to cancel asynchronous operations. It emerged as a solution to the problem of lacking a universal way to cancel promises and asynchronous operations in the language.
AbortController creates a cancellation signal that can be passed to asynchronous operations:
const controller = new AbortController();
const { signal } = controller;
// Pass signal to asynchronous operation
fetch('/api/data', { signal });
// Cancel operation
controller.abort();The most common use case:
const controller = new AbortController();
fetch('/api/long-operation', {
signal: controller.signal
})
.then(response => response.json())
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request cancelled');
}
});
// Cancel request
controller.abort();Timers can be cancelled using AbortController:
function delay(ms, signal) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(resolve, ms);
// Listen for cancellation signal
signal.addEventListener('abort', () => {
clearTimeout(timeoutId);
reject(new DOMException('Operation cancelled', 'AbortError'));
});
});
}function fetchWithTimeout(url, timeoutMs) {
const controller = new AbortController();
// Cancel on timeout
const timeoutId = setTimeout(() => {
controller.abort();
}, timeoutMs);
return fetch(url, { signal: controller.signal })
.finally(() => clearTimeout(timeoutId));
}const controller = new AbortController();
// Cancel all requests on navigation
window.addEventListener('beforeunload', () => {
controller.abort();
});
fetch('/api/data', { signal: controller.signal });const controller = new AbortController();
const { signal } = controller;
// Check if signal is cancelled
if (signal.aborted) {
console.log('Operation already cancelled');
}signal.addEventListener('abort', () => {
console.log('Operation cancelled');
});// ❌ Ignoring cancellation errors
fetch('/api/data', { signal })
.then(response => console.log(response));
// ✅ Properly handling errors
fetch('/api/data', { signal })
.then(response => console.log(response))
.catch(error => {
if (error.name === 'AbortError') {
// Expected cancellation, not an error
console.log('Request cancelled');
} else {
// Real error
console.error('Request error:', error);
}
});Calling abort() on already completed operations doesn’t cause errors but has no effect.
AbortController is supported by all modern browsers. Polyfill required for older browsers.
AbortController is a powerful tool for managing asynchronous operations, allowing efficient cancellation of requests and resource freeing.
What will happen when executing this code and how to improve it?
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
.then(response => response.json())
.then(data => console.log(data));
// Cancel after 2 seconds
setTimeout(() => {
controller.abort();
}, 2000);Answer: When executing this code:
/api/data will startcontroller.abort() will be calledImproved version:
const controller = new AbortController();
fetch('/api/data', { signal: controller.signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request was cancelled');
} else {
console.error('Request error:', error);
}
});
// Cancel after 2 seconds
setTimeout(() => {
controller.abort();
}, 2000);Explanation:
It’s important to understand that AbortController is not instant cancellation, but a signal that asynchronous operations can check and respond to appropriately.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪