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 function retryOperation(operation, maxRetries, delay) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (error) {
lastError = error;
await new Promise(resolve => setTimeout(resolve, delay));
}
}
throw lastError;
}
带指数退避的重试
指数退避算法能有效避免资源竞争。示例代码:
async function retryWithBackoff(operation, maxRetries, initialDelay) {
let delay = initialDelay;
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (error) {
lastError = error;
await new Promise(resolve => setTimeout(resolve, delay));
delay *= 2; // 指数增加延迟时间
}
}
throw lastError;
}
使用第三方库实现
现有库如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,
minTimeout: 1000
});
}
重试策略定制
可根据需求定制重试条件,例如只对特定错误重试:
function shouldRetry(error) {
return error.code === 'ECONNRESET' || error.code === 'ETIMEDOUT';
}
async function retryWithCondition(operation, maxRetries) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
return await operation();
} catch (error) {
if (!shouldRetry(error)) throw error;
lastError = error;
}
}
throw lastError;
}
取消重试机制
实现可取消的重试操作:

function retryWithCancel(operation, maxRetries, delay) {
let cancel;
const promise = new Promise(async (resolve, reject) => {
let cancelled = false;
cancel = () => { cancelled = true; };
let lastError;
for (let i = 0; i < maxRetries; i++) {
if (cancelled) return reject(new Error('Cancelled'));
try {
return resolve(await operation());
} catch (error) {
lastError = error;
await new Promise(r => setTimeout(r, delay));
}
}
reject(lastError);
});
return { promise, cancel };
}
这些方法覆盖了从基础到高级的重试场景,可根据具体需求选择合适的实现方式。






