Skip to content

Commit 21930fe

Browse files
[Updated] Added AbortController API to the cancellation topic; (#56)
1 parent 6f09322 commit 21930fe

File tree

1 file changed

+53
-2
lines changed

1 file changed

+53
-2
lines changed

posts/en/cancellation.md

Lines changed: 53 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,30 @@ next_title: 'URL-Encoding Bodies'
66
next_link: '/docs/urlencoded'
77
---
88

9-
You can cancel a request using a *cancel token*.
9+
## AbortController
10+
11+
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:
12+
13+
```js
14+
const controller = new AbortController();
15+
16+
axios.get('/foo/bar', {
17+
signal: controller.signal
18+
}).then(function(response) {
19+
//...
20+
});
21+
// cancel the request
22+
controller.abort()
23+
```
24+
25+
## CancelToken `deprecated`
26+
27+
You can also cancel a request using a *CancelToken*.
1028

1129
> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
1230
31+
> This API is deprecated since `v0.22.0` and shouldn't be used in new projects
32+
1333
You can create a cancel token using the `CancelToken.source` factory as shown below:
1434

1535
```js
@@ -53,4 +73,35 @@ axios.get('/user/12345', {
5373
cancel();
5474
```
5575

56-
> Note: you can cancel several requests with the same cancel token.
76+
> Note: you can cancel several requests with the same cancel token / signal.
77+
78+
During the transition period, you can use both cancellation APIs, even for the same request:
79+
80+
```js
81+
const controller = new AbortController();
82+
83+
const CancelToken = axios.CancelToken;
84+
const source = CancelToken.source();
85+
86+
axios.get('/user/12345', {
87+
cancelToken: source.token,
88+
signal: controller.signal
89+
}).catch(function (thrown) {
90+
if (axios.isCancel(thrown)) {
91+
console.log('Request canceled', thrown.message);
92+
} else {
93+
// handle error
94+
}
95+
});
96+
97+
axios.post('/user/12345', {
98+
name: 'new name'
99+
}, {
100+
cancelToken: source.token
101+
})
102+
103+
// cancel the request (the message parameter is optional)
104+
source.cancel('Operation canceled by the user.');
105+
// OR
106+
controller.abort(); // the message parameter is not supported
107+
```

0 commit comments

Comments
 (0)