0 day streak
javascript / intermediate
Snippet

Async Cancellation with AbortController

AbortController provides a standard way to cancel asynchronous operations. By passing an AbortSignal to a task, you can react to an 'abort' event and clean up resources.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const controller = new AbortController();
const { signal } = controller;
function performTask(signal) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => resolve('Task Complete'), 5000);
signal.addEventListener('abort', () => {
clearTimeout(timeout);
reject(new Error('Task Cancelled'));
});
});
}
// Trigger cancellation after 1 second
setTimeout(() => controller.abort(), 1000);
performTask(signal)
.then(console.log)
.catch(err => console.error(err.message));
Breakdown
1
const controller = new AbortController();
Creates an instance to control the cancellation process.
2
signal.addEventListener('abort', ...)
Listens for the signal to cancel and executes cleanup logic.