@ocap/util
Version:
utils shared across multiple forge js libs, works in both node.js and browser
31 lines (30 loc) • 978 B
JavaScript
/* eslint-disable no-await-in-loop */
function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
// eslint-disable-next-line consistent-return
export async function withRetry(handle, { retryLimit = 30, backoff = { baseDelay: 20, maxDelay: 1000 }, shouldRetry = () => true, onError = () => { }, } = {}) {
let attempt = 0;
let lastError;
while (attempt <= retryLimit) {
attempt++;
try {
const result = await handle();
return result;
}
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);
}
}
}