js实现retry
实现重试机制的几种方法
在JavaScript中实现重试机制可以通过多种方式完成,以下是几种常见的实现方法:
使用递归函数实现重试
function retryOperation(operation, maxRetries, delay) {
return new Promise((resolve, reject) => {
function attempt(retryCount) {
operation()
.then(resolve)
.catch(error => {
if (retryCount >= maxRetries) {
reject(error);
} else {
setTimeout(() => attempt(retryCount + 1), delay);
}
});
}
attempt(0);
});
}
使用async/await实现重试

async function retryAsyncOperation(operation, maxRetries, delay) {
let lastError;
for (let i = 0; i < maxRetries; i++) {
try {
const result = await operation();
return result;
} catch (error) {
lastError = error;
if (i < maxRetries - 1) {
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
throw lastError;
}
使用第三方库实现重试
多个流行库提供了内置的重试功能:

axios-retry:为axios请求添加重试功能p-retry:为Promise操作提供重试功能async-retry:简单易用的异步重试库
指数退避策略实现
function exponentialBackoff(operation, maxRetries, initialDelay) {
return new Promise((resolve, reject) => {
function attempt(retryCount) {
operation()
.then(resolve)
.catch(error => {
if (retryCount >= maxRetries) {
reject(error);
} else {
const delay = initialDelay * Math.pow(2, retryCount);
setTimeout(() => attempt(retryCount + 1), delay);
}
});
}
attempt(0);
});
}
带条件判断的重试实现
function conditionalRetry(operation, shouldRetry, maxRetries, delay) {
return new Promise((resolve, reject) => {
function attempt(retryCount) {
operation()
.then(resolve)
.catch(error => {
if (retryCount >= maxRetries || !shouldRetry(error)) {
reject(error);
} else {
setTimeout(() => attempt(retryCount + 1), delay);
}
});
}
attempt(0);
});
}
每种实现方法适用于不同场景,选择哪种取决于具体需求。递归方法适合简单场景,async/await版本更易读,第三方库可以减少重复代码,指数退避适合网络请求,条件重试提供了更灵活的控制。






