capypad
0 day streak
javascript / intermediate
Snippet

Clean Async Cancellation with AbortController

The AbortController interface allows you to abort one or more Web requests as and when desired. This is essential for intermediate developers to handle component unmounting in frameworks or to prevent race conditions when multiple requests are triggered sequentially.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const controller = new AbortController();
const { signal } = controller;
 
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data', { signal });
return await response.json();
} catch (err) {
if (err.name === 'AbortError') {
console.log('Fetch aborted');
}
}
}
 
fetchData();
controller.abort(); // Immediately cancels the fetch
Breakdown
1
const controller = new AbortController();
Initializes a new controller instance to manage cancellation signals.
2
{ signal }
Extracts the AbortSignal object to be passed to async operations like 'fetch'.
3
controller.abort();
Triggers the abort signal, causing any associated requests to fail with an 'AbortError'.