代码实现思路
- 定义最大重试次数和初始重试间隔时间。
- 在
axios
请求中设置timeout
。
- 捕获
axios
请求的超时错误,根据重试次数决定是否进行重试,每次重试增加间隔时间。
关键代码片段
const axios = require('axios');
// 最大重试次数
const maxRetries = 3;
// 初始重试间隔时间(秒)
let retryInterval = 1;
async function makeRequestWithRetry(url, options = {}) {
let retries = 0;
while (retries < maxRetries) {
try {
// 设置超时时间
options.timeout = 5000;
const response = await axios(url, options);
return response;
} catch (error) {
if (error.code === 'ECONNABORTED' && error.message.includes('timeout')) {
retries++;
if (retries < maxRetries) {
console.log(`请求超时,重试第 ${retries} 次,等待 ${retryInterval} 秒...`);
await new Promise(resolve => setTimeout(resolve, retryInterval * 1000));
retryInterval++;
} else {
console.log('达到最大重试次数,请求失败');
throw error;
}
} else {
throw error;
}
}
}
}
// 使用示例
makeRequestWithRetry('https://example.com/api/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('请求最终失败:', error);
});