Skip to content

Commit 74daad4

Browse files
author
Amr Abdelkader
committed
docs: add cancelToken usage in docs
1 parent 0cc9471 commit 74daad4

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

docs/usage.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,54 @@ methods: {
3535
}
3636
}
3737
```
38+
39+
### Cancel token
40+
41+
You can cancel a request using a *cancel token*.
42+
43+
> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
44+
45+
You can create a cancel token using the `CancelToken.source` factory as shown below:
46+
47+
```js
48+
const CancelToken = this.$axios.CancelToken;
49+
const source = CancelToken.source();
50+
51+
this.$axios.$get('/user/12345', {
52+
cancelToken: source.token
53+
}).catch(function (thrown) {
54+
if (this.$axios.isCancel(thrown)) {
55+
console.log('Request canceled', thrown.message);
56+
} else {
57+
// handle error
58+
}
59+
});
60+
61+
this.$axios.$post('/user/12345', {
62+
name: 'new name'
63+
}, {
64+
cancelToken: source.token
65+
})
66+
67+
// cancel the request (the message parameter is optional)
68+
source.cancel('Operation canceled by the user.');
69+
```
70+
71+
You can also create a cancel token by passing an executor function to the `CancelToken` constructor:
72+
73+
```js
74+
const CancelToken = this.$axios.CancelToken;
75+
let cancel;
76+
77+
this.$axios.$get('/user/12345', {
78+
cancelToken: new CancelToken(function executor(c) {
79+
// An executor function receives a cancel function as a parameter
80+
cancel = c;
81+
})
82+
});
83+
84+
// cancel the request
85+
cancel();
86+
```
87+
88+
> Note: you can cancel several requests with the same cancel token.

0 commit comments

Comments
 (0)