js retry 实现
实现 JavaScript 重试机制的几种方法
使用递归实现重试
通过递归函数可以在失败时重新调用自身,直到达到最大重试次数或成功为止。
function retryOperation(operation, maxRetries, delay) {
return new Promise((resolve, reject) => {
operation()
.then(resolve)
.catch(error => {
if (maxRetries <= 0) {
return reject(error);
}
setTimeout(() => {
retryOperation(operation, maxRetries - 1, delay)
.then(resolve)
.catch(reject);
}, delay);
});
});
}
使用循环实现重试
通过循环和async/await可以更直观地实现重试逻辑。

async function retryOperation(operation, maxRetries, delay) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
const result = await operation();
return result;
} catch (error) {
lastError = error;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw lastError;
}
带指数退避的重试
指数退避算法可以在每次重试时增加延迟时间,避免短时间内频繁重试。

async function retryWithBackoff(operation, maxRetries, initialDelay) {
let currentDelay = initialDelay;
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
const result = await operation();
return result;
} catch (error) {
lastError = error;
await new Promise(resolve => setTimeout(resolve, currentDelay));
currentDelay *= 2;
}
}
throw lastError;
}
使用现成库实现
许多现成的JavaScript库提供了重试功能,如async-retry和p-retry。
使用p-retry示例:
const pRetry = require('p-retry');
async function run() {
return pRetry(async () => {
const result = await fetch('https://example.com');
return result;
}, {
retries: 5,
onFailedAttempt: error => {
console.log(`Attempt ${error.attemptNumber} failed.`);
}
});
}
重试策略的最佳实践
- 设置合理的最大重试次数,避免无限重试
- 考虑添加延迟,特别是对API调用
- 对于非幂等操作要谨慎使用重试
- 记录重试次数和失败原因有助于调试
- 对于特定错误类型可能需要不同的重试策略






