如何实现axios取消请求的操作呢?
1.在这里有一个重要的思想代码:
可以通过传递一个 executor 函数到 CancelToken
的构造函数来创建一个 cancel token:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
})
});
// 取消请求
cancel();
2.具体的实例举例:
<script>
const btn=document.querySelectorAll("button")
let cancel=null
const CancelToken = axios.CancelToken;
btn[0].onclick=function(){
// 检测上一次请求是否完成
if(cancel!=null){
// 检测到上一次请求未完成,清除请求
cancel()
}
axios(
{
method:'GET',
url:'http://localhost/post',
cancelToken: new CancelToken(function executor(c) {
// executor 函数接收一个 cancel 函数作为参数
cancel = c;
})
}
).then(response=>{
console.log(response);
cancel=null;
// 请求成功就初始化请求了
})
}
// 在这里表示按下第二个按钮,那么就取消请求了
btn[2].onclick=function(){
cancel()
}
</script>