vue中axios请求超时后设置重连次数和重连时间间隔

vue中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);
    });
});

使用的时候

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

配置项

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

总结

写了一个全局的重连的方法,有不对的地方欢迎指出

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容