23 lines
No EOL
622 B
TypeScript
23 lines
No EOL
622 B
TypeScript
export async function retryWithExponentialBackoff<T>(
|
|
fn: () => Promise<T>,
|
|
maxRetries: number = 3,
|
|
delayMs: number = 1000
|
|
): Promise<T> {
|
|
let lastError: Error | undefined
|
|
|
|
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
|
try {
|
|
return await fn()
|
|
} catch (error) {
|
|
lastError = error instanceof Error ? error : new Error(String(error))
|
|
|
|
if (attempt < maxRetries) {
|
|
console.log(`Attempt ${attempt} failed, retrying in ${delayMs}ms...`)
|
|
await new Promise(resolve => setTimeout(resolve, delayMs))
|
|
delayMs *= 2
|
|
}
|
|
}
|
|
}
|
|
|
|
throw lastError
|
|
} |