UNPKG

@lodestar/utils

Version:

Utilities required across multiple lodestar packages

44 lines 1.45 kB
import { ErrorAborted } from "./errors.js"; import { sleep } from "./sleep.js"; /** * Retry a given function on error. * @param fn Async callback to retry. Invoked with 1 parameter * A Number identifying the attempt. The absolute first attempt (before any retries) is 1 * @param opts */ export async function retry(fn, opts) { const maxRetries = opts?.retries ?? 5; // Number of retries + the initial attempt const maxAttempts = maxRetries + 1; const shouldRetry = opts?.shouldRetry; const onRetry = opts?.onRetry; let lastError = Error("RetryError"); for (let i = 1; i <= maxAttempts; i++) { // If not the first attempt if (i > 1) { if (opts?.signal?.aborted) { throw new ErrorAborted("retry"); } // Invoke right before retrying onRetry?.(lastError, i); } try { return await fn(i); } catch (e) { lastError = e; if (i === maxAttempts) { // Reached maximum number of attempts, there's no need to check if we should retry break; } if (shouldRetry && !shouldRetry(lastError)) { break; } if (opts?.retryDelay !== undefined) { await sleep(opts?.retryDelay, opts?.signal); } } } throw lastError; } //# sourceMappingURL=retry.js.map