UNPKG

@ocap/util

Version:

utils shared across multiple forge js libs, works in both node.js and browser

31 lines (29 loc) 754 B
//#region src/retry.ts function wait(ms) { return new Promise((resolve) => { setTimeout(resolve, ms); }); } async function withRetry(handle, { retryLimit = 30, backoff = { baseDelay: 20, maxDelay: 1e3 }, shouldRetry = () => true, onError = () => {} } = {}) { let attempt = 0; let lastError; while (attempt <= retryLimit) { attempt++; try { return await handle(); } catch (error) { if (!shouldRetry(error) || attempt > retryLimit) throw error; lastError = error; if (onError) await onError(lastError, attempt); const { baseDelay, maxDelay } = backoff; const delay = Math.min(maxDelay, baseDelay * 2 ** attempt); await wait(Math.random() * delay); } } throw lastError; } //#endregion exports.withRetry = withRetry;