Skip to content
Permalink
Browse files

feat: add `CancelToken` and `isCancel` to axios instance (#292)

  • Loading branch information
3b3ziz authored and pi0 committed Oct 23, 2019
1 parent 0d616f8 commit 474910bd875f2d1f6bf0e39e511db87b08673cdc
Showing with 52 additions and 0 deletions.
  1. +50 −0 docs/usage.md
  2. +2 −0 lib/plugin.js
@@ -35,3 +35,53 @@ methods: {
}
}
```

### Cancel token

You can cancel a request using a _cancel token_.

> The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises).
You can create a cancel token using the `CancelToken.source` factory as shown below:

```js
const source = this.$axios.CancelToken.source()
this.$axios.$get('/user/12345', {
cancelToken: source.token
}).catch(error => {
if (this.$axios.isCancel(error)) {
console.log('Request canceled', error)
} else {
// handle error
}
})
this.$axios.$post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.')
```

You can also create a cancel token by passing an executor function to the `CancelToken` constructor:

```js
const { CancelToken } = this.$axios
let cancel
this.$axios.$get('/user/12345', {
cancelToken: new CancelToken(c => {
// An executor function receives a cancel function as a parameter
cancel = c
}),
})
// cancel the request
cancel()
```

> Note: you can cancel several requests with the same cancel token.
@@ -184,6 +184,8 @@ export default (ctx, inject) => {

// Create new axios instance
const axios = Axios.create(axiosOptions)
axios.CancelToken = Axios.CancelToken
axios.isCancel = Axios.isCancel

// Extend axios proto
extendAxiosInstance(axios)

0 comments on commit 474910b

Please sign in to comment.
You can’t perform that action at this time.