[英]How do I cancel a ongoing GET request with axios
我有一個輸入字段,onChange 它將我輸入字段的值發送到 API。 因此,api 將開始獲取所有數據。 但是當我再次繼續輸入時,我希望取消之前的請求。
我正在使用 axios 提出我的請求並嘗試查看文檔,但我似乎無法弄清楚它是如何工作的,有人可以解釋一下如何做到這一點嗎?
這是我的 function ,每個新輸入都會調用它:
const onChange = (value) => {
setTimeout(async() => {
let result = []
if (y === "keyword") result = await AutoSuggestionKeyword({
value: value
});
else {
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
await axios.get(`https://${api_uri}/${value.toLowerCase()}`)
.catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
}).then(resp => {
console.log(resp)
});
source.cancel();
}
}, 500)
}
您需要在請求中提供cancelToken
,
axios.get(`https://${api_uri}/${value.toLowerCase()}`, {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
I don't think you can cancel an HTTP request
, but what you can do is wrap it in debounce function, debounce function wait for a certain time before calling the callback or function you wrap or pass on it.
您可以簡單地 google debounce,它會為您提供可以使用的文章或 npm 包。
我認為這篇文章也有您要解決的相同問題
快樂編碼
編輯 1:是的,所以您可以取消 http 請求,請參閱下面的評論
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.