UNPKG

magnitude-core

Version:
31 lines (30 loc) 1.11 kB
export async function retry(fn, options = {}) { const { retries = 3, delay = 0, maxDelay = Infinity, exponential = false, throwOnExhaustion = true, // Now defaults to true retryIf = () => true, onRetry } = options; const multiplier = exponential === true ? 2 : exponential || 1; for (let attempt = 0; attempt <= retries; attempt++) { try { return await fn(); } catch (error) { if (!(error instanceof Error)) { throw new Error(`Non-Error thrown: ${String(error)}`); } if (attempt === retries || !retryIf(error)) { if (throwOnExhaustion) { throw error; } return null; } if (onRetry) { onRetry(error, attempt + 1); } if (delay > 0) { const currentDelay = Math.min(delay * Math.pow(multiplier, attempt), maxDelay); await new Promise(resolve => setTimeout(resolve, currentDelay)); } } } // Unreachable return null; }