Files
cloudron-box/src/promise-retry.js
T
2025-07-25 01:30:27 +02:00

26 lines
813 B
JavaScript

'use strict';
exports = module.exports = promiseRetry;
const assert = require('assert'),
timers = require('timers/promises'),
util = require('util');
async function promiseRetry(options, asyncFunction) {
assert.strictEqual(typeof options, 'object');
assert(util.types.isAsyncFunction(asyncFunction));
const { times, interval } = options;
for (let i = 0; i < times; i++) {
try {
return await asyncFunction(i+1 /* attempt */);
} catch (error) {
if (i === times - 1) throw error;
if (options.retry && !options.retry(error)) throw error; // no more retry
if (options.debug) options.debug(`Attempt ${i+1} failed. Will retry: ${error.message} ${error.stack}`);
await timers.setTimeout(interval);
}
}
}