Skip to content

Commit b8204c6

Browse files
Update cancellation.md - Abort examples + use case (#98)
Co-authored-by: Jay <[email protected]>
1 parent 03bf42d commit b8204c6

File tree

1 file changed

+39
-2
lines changed

1 file changed

+39
-2
lines changed

posts/en/cancellation.md

+39-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,19 @@ next_title: 'URL-Encoding Bodies'
66
next_link: '/docs/urlencoded'
77
---
88

9-
## AbortController
9+
## Cancelling requests
10+
11+
Setting the `timeout` property in an axios call handles **response** related timeouts.
12+
13+
In some cases (e.g. network connection becomes unavailable) an axios call would benefit from cancelling the **connection** early. Without cancellation, the axios call can hang until the parent code/stack times out (might be a few minutes in a server-side applications).
14+
15+
To terminate an axios call you can use following methods:
16+
- `signal`
17+
- `cancelToken` (deprecated)
18+
19+
Combining `timeout` and cancellation method (e.g. `signal`) should cover **response** related timeouts AND **connection** related timeouts.
20+
21+
### `signal`: AbortController
1022

1123
Starting from `v0.22.0` Axios supports [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to cancel requests in fetch API way:
1224

@@ -22,7 +34,32 @@ axios.get('/foo/bar', {
2234
controller.abort()
2335
```
2436

25-
## CancelToken `deprecated`
37+
Example with a timeout using latest [`AbortSignal.timeout()`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal/timeout) API [nodejs 17.3+]:
38+
```js
39+
axios.get('/foo/bar', {
40+
signal: AbortSignal.timeout(5000) //Aborts request after 5 seconds
41+
}).then(function(response) {
42+
//...
43+
});
44+
```
45+
46+
Example with a timeout helper function:
47+
```js
48+
function newAbortSignal(timeoutMs) {
49+
const abortController = new AbortController();
50+
setTimeout(() => abortController.abort(), timeoutMs || 0);
51+
52+
return abortController.signal;
53+
}
54+
55+
axios.get('/foo/bar', {
56+
signal: newAbortSignal(5000) //Aborts request after 5 seconds
57+
}).then(function(response) {
58+
//...
59+
});
60+
```
61+
62+
### CancelToken `deprecated`
2663

2764
You can also cancel a request using a *CancelToken*.
2865

0 commit comments

Comments
 (0)