javascript - Anulează toate cererile axios în așteptare și creează altele noi
Folosesc axios pentru cereri API, am o situație în care vreau să întrerup toate cererile în curs/în așteptare și să creez altele noi cu un alt API.
Am încercat codul de mai jos
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();
}
Practic, vreau să anulez cererile API /search_old și search_old_second și să creez search_new.
Răspuns #1
Poți folosi anularea
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.');
Răspunsul #2
Nu sunt sigur în legătură cu asta, dar din câte îmi amintesc, ar fi ceva de genul acesta.
Preluat din documentația 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);
