Listening to the abort Event
You'll learn how to attach event listeners to an AbortSignal to perform custom cleanup when an operation is aborted.
Why Listen to the Abort Event?
When you call abort() on an AbortController, the associated signal doesn't just cancel Fetch requests—it fires an abort event that you can listen to. This lets you run custom cleanup code, log cancellations, update UI state, or cancel related operations that aren't directly tied to the aborted request.
Think of it like a fire alarm: when it goes off, not only does the sprinkler system activate automatically, but you can also listen for the alarm to evacuate people and secure valuables—your own custom responses.
Attaching an Event Listener
Use addEventListener() on the AbortSignal to register a handler:
const controller = new AbortController();
const signal = controller.signal;
signal.addEventListener('abort', () => {
console.log('Operation was aborted!');
// Custom cleanup logic here
});
// Later, trigger the abort
controller.abort();
// Logs: "Operation was aborted!"
This is useful when you have multiple things happening—perhaps a Fetch request and a timer or animation—that all need to stop together.
Practical Use Case
const controller = new AbortController();
signal.addEventListener('abort', () => {
console.log('Search cancelled, resetting UI...');
// Clear loading spinner, reset input state, etc.
});
fetch('/api/search', { signal: controller.signal })
.catch(err => {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
}
});
controller.abort(); // Triggers both the event listener and fetch cancellation
Key Takeaway: Listening to the abort event on an AbortSignal lets you run custom cleanup or side effects whenever abort() is called, making cancellation logic more flexible and centralized.