@ginden/blinkstick-v2
Version:
Improved Blickstick API for Node.js
31 lines • 1.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.retryNTimes = retryNTimes;
const promises_1 = require("node:timers/promises");
/**
* Retries a function n times with an increasing delay.
* Delays are 0, 10, 40, 90, 160, ... ms by default
*/
async function retryNTimes(maxRetries, fn, errorData, wait = (n) => n === 0 ? promises_1.scheduler.yield() : promises_1.scheduler.wait(10 * n ** 2)) {
// const wait = (ms: number) => (ms === 0 ? scheduler.yield() : scheduler.wait(ms));
if (maxRetries === 1) {
return await fn();
}
let error = null;
for (let retries = 0; retries < maxRetries; retries++) {
try {
return await fn();
}
catch (ex) {
error ??= ex;
await wait(retries);
}
}
const syntheticError = new Error(`Failed after ${maxRetries} retries`);
Error.captureStackTrace(syntheticError, retryNTimes);
throw Object.assign(error, {
syntheticStack: syntheticError.stack,
...errorData,
});
}
//# sourceMappingURL=retry-n-times.js.map