• axios设置请求超时时间与超时取消请求


    一、设置超时时间,超时取消请求

    场景:调用第三方接口不太稳定,需要设置超时时间,超时取消请求并提示连接超时

    使用cancelToken参数,axios自带cancelToken参数

    1.axios请求外部

    const CancelToken = axios.CancelToken;
        let cancel;
        let timer = setTimeout(() => {
            cancel();
            this.$message.error("连接超时,请检查网络!")
        }, 10000);

    2.axios请求内部

    this.axios({
         method: "post",
         url,
         data,
         cancelToken: new CancelToken(function executor(c) {
             cancel = c;
         }),
     })
     .then((response) => {
         clearTimeout(timer);
         if (!response.data.hasError) {
             this.$message.success("数据获取成功!");
             const results = response.data.result;
         } else {
             this.$message.error("数据获取失败!");
         }
     })
     .catch((error) => {
         clearTimeout(timer);
         if (error.response) {
             this.$message.error("数据获取失败!");
         }
     });

    注意: 可以使用同一个 cancel token 取消多个请求

    二、设置超时时间,超时重新请求

    配置axios拦截器

    axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
        var config = err.config;
        // If config does not exist or the retry option is not set, reject
        if(!config || !config.retry) return Promise.reject(err);
        
        // Set the variable for keeping track of the retry count
        config.__retryCount = config.__retryCount || 0;
        
        // Check if we've maxed out the total number of retries
        if(config.__retryCount >= config.retry) {
            // Reject with the error
            return Promise.reject(err);
        }
        
        // Increase the retry count
        config.__retryCount += 1;
        
        // Create new promise to handle exponential backoff
        var backoff = new Promise(function(resolve) {
            setTimeout(function() {
                resolve();
            }, config.retryDelay || 1);
        });
        
        // Return the promise in which recalls axios to retry the request
        return backoff.then(function() {
            return axios(config);
        });
    });

    使用的时候,

    1.retry - 第一次请求失败后重试请求的次数。
    2.retryDelay -在失败请求之间等待的毫秒数(默认为1)。

    axios.get('/some/endpoint', { retry: 5, retryDelay: 1000 })
        .then(function(res) {
            console.log('success', res.data);
        })
        .catch(function(err) {
            console.log('failed', err);
        });

     参考:https://www.jianshu.com/p/e58ff85b2a91

  • 相关阅读:
    勤娇猛伤湃负纶孪跋贡那睦
    C#
    日记造词——有世无解
    chrome主页被hao123篡改,怎么改回来?
    不知还有人遇到这个问题没有:数据库 'xxx' 的版本为 706,无法打开。此服务器支持 661 版及更低版本。不支持降级路径。
    JQuery插件(三)分页插件-JqPaginator
    Jquery插件(二) filterMore仿京东筛选插件
    Jquery插件(一) webupload上传插件
    hadoop安装配置
    亚马逊aws ubuntu设置root 密码方式登录方法
  • 原文地址:https://www.cnblogs.com/younghxp/p/14307156.html
Copyright © 2020-2023  润新知