[英]Abort all axios pending requests and create new
I am using axios
for API requests, I have a situation where I want to abort all running/pending requests and create new with another API.我正在将
axios
用于 API 请求,我有一种情况,我想中止所有正在运行/待处理的请求并使用另一个 API 创建新请求。
Have tried below code试过下面的代码
async getOldResponse() {
const response_old: any = await this.axios.post("/search_old", this.searchData);
console.log(response_old)
}
async getOldOtherResponse() {
const response_old_second: any = await this.axios.post("/search_old_second", this.searchData);
console.log(response_old_second);
}
async getNewSearch() {
// here i want to cancel all pending requests.
const CancelToken = this.axios.CancelToken;
const source = CancelToken.source();
source.cancel('All previous pending request cancelled');
const response: any = await this.axios.post("/search_new", this.searchData);
console.log(response);
}
ngOnInit() {
this.getOldResponse();
this.getOldOtherResponse();
this.getNewSearch();
}
Basically I want to abort /search_old
& search_old_second
API requests and create search_new
.基本上我想中止
/search_old
& search_old_second
API 请求并创建search_new
。
You can use cancellation您可以使用取消
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
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.');
I am not sure about this, but from what i remember it would be something like this.我不确定这一点,但据我所知,它会是这样的。
Taken from axios documentation https://github.com/axios/axios取自 axios 文档https://github.com/axios/axios
/* create cancel token */
const CancelToken = this.axios.CancelToken;
const source = CancelToken.source();
/* fire requests whose only purpose is to be canceled */
const response_old: any = await this.axios({
method: 'post',
cancelToken: source.token,
url: '/search_old',
data: this.searchData
})
const response_old_second: any = await this.axios({
method: 'post',
cancelToken: source.token,
url: '/search_old_second',
data: this.searchData
})
/* cancel all previous pending requests */
source.cancel('optional message')
/* fire new request */
const response: any = await this.axios.post("/search_new", this.searchData);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.