axios 利用interceptors(拦截器)完美解决自动重试问题。
// 重试次数,共请求2次
axios.defaults.retry = 1
// 请求的间隙
axios.defaults.retryDelay = 1000
var axios = require('axios');
axios.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
var config = err.config;
// 如果配置不存在或未设置重试选项,则拒绝
if (!config || !config.retry) return Promise.reject(err);
// 设置变量以跟踪重试次数
config.__retryCount = config.__retryCount || 0;
// 判断是否超过总重试次数
if (config.__retryCount >= config.retry) {
// 返回错误并退出自动重试
return Promise.reject(err);
}
// 增加重试次数
config.__retryCount += 1;
//打印当前重试次数
console.log(config.url +' 自动重试第' + config.__retryCount + '次');
// 创建新的Promise
var backoff = new Promise(function (resolve) {
setTimeout(function () {
resolve();
}, config.retryDelay || 1);
});
// 返回重试请求
return backoff.then(function () {
return axios(config);
});
});
axios.get('https://www.google.com', {
retry: 5,
retryDelay: 1000,
timeout: 6000
})
.then(function (res) {
console.log('success', res.data);
})
.catch(function (err) {
console.log('failed', err);
});
https://www.google.com 自动重试第1次
https://www.google.com 自动重试第2次
https://www.google.com 自动重试第3次
https://www.google.com 自动重试第4次
https://www.google.com 自动重试第5次
https://github.com/axios/axios/issues/164#issuecomment-327837467
如果这篇文章对你有所帮助,可以通过下边的“打赏”功能进行小额的打赏。
本网站部分内容来源于互联网,如有侵犯版权请来信告知,我们将立即处理。