axios取消请求

如何实现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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值