javascript Axios重试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript Axios重试相关的知识,希望对你有一定的参考价值。

import axios from 'axios';

export default (function axiosRetry() {
  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);
      });
  });
})();
import axiosRetry from '../helpers/axios-retry';

axios.get('/some/endpoint', { retry: 5, retryDelay: 1000 })
    .then(function(res) {
        console.log('success', res.data);
    })
    .catch(function(err) {
        console.log('failed', err);
    });
    
// retry - Number of times to retry the request after first failed request.
// retryDelay - Number of milliseconds to wait in between failed requests (defaults to 1).

以上是关于javascript Axios重试的主要内容,如果未能解决你的问题,请参考以下文章

Axios使用拦截器全局处理请求重试

Axios 中的单元测试拦截器逻辑

axios增强版封装

javascript Ajax重试

如何让 axios 拦截器重试原始请求?

如何做出递归承诺