0 day streak
javascript / intermediate
Snippet

Managing Async Timeouts with AbortController

AbortController allows you to cancel asynchronous tasks like fetch requests or file operations. It provides a signal that can be passed to various APIs, enabling precise control over request lifecycles and timeouts to prevent hanging processes.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const controller = new AbortController();
const signal = controller.signal;
// Trigger abort after 1 second
const timeoutId = setTimeout(() => controller.abort(), 1000);
try {
const response = await fetch('https://api.example.com/data', { signal });
const data = await response.json();
clearTimeout(timeoutId);
} catch (err) {
if (err.name === 'AbortError') {
console.error('Request was cancelled due to timeout');
}
}
nodejs
Breakdown
1
const controller = new AbortController();
Initializes a new controller instance to manage the abort signal.
2
const signal = controller.signal;
Extracts the signal object to be passed to async functions.
3
controller.abort()
Signals the cancellation of all operations associated with this signal.
4
if (err.name === 'AbortError')
Identifies that the error was specifically caused by the abort signal.