javascript / intermediate
Snippet
Timeout handling with AbortController
In Node.js, AbortController is the standard way to cancel asynchronous operations like fetch requests. By passing the controller's signal to the fetch call, you can programmatically stop the request if it takes too long.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 5000);try {const response = await fetch('https://api.example.com/data', {signal: controller.signal});const data = await response.json();} catch (error) {if (error.name === 'AbortError') {console.error('Request timed out');}} finally {clearTimeout(timeoutId);}
nodejs
Breakdown
1
const controller = new AbortController();
Creates a new instance of AbortController to manage the cancellation signal.
2
signal: controller.signal
Links the fetch request to the controller so it can be aborted.
3
controller.abort()
Triggers the cancellation, causing the fetch promise to reject with an AbortError.