Files
cloudron-box/src/promise-retry.js
Girish Ramakrishnan 12e073e8cf use node: prefix for requires
mostly because code is being autogenerated by all the AI stuff using
this prefix. it's also used in the stack trace.
2025-08-14 12:55:35 +05:30

26 lines
878 B
JavaScript

'use strict';
exports = module.exports = promiseRetry;
const assert = require('node:assert'),
timers = require('timers/promises'),
util = require('node: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 (options.debug) options.debug(`Attempt ${i+1} failed. Will retry: ${error.message} ${i === times-1 ? error.stack : ''}`); // only print stack on last error
if (i === times - 1) throw error;
if (options.retry && !options.retry(error)) throw error; // no more retry
await timers.setTimeout(interval);
}
}
}