Files
zhuiguang-ai/scripts/lib/retry.mjs
T

18 lines
571 B
JavaScript

async function withRetry(fn, { maxRetries = 3, baseDelay = 1000, label = "operation" } = {}) {
let lastError;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (attempt < maxRetries) {
const delay = baseDelay * Math.pow(2, attempt - 1);
console.warn(` ⚠ ${label} 第${attempt}次失败,${delay / 1000}s后重试...`);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
}
throw lastError;
}
export { withRetry };