Files
cloudron-box/src/promise-retry.js
Girish Ramakrishnan 43f86674b4 Remove delay module
2022-04-15 07:52:35 -05:00

26 lines
780 B
JavaScript

'use strict';
exports = module.exports = promiseRetry;
const assert = require('assert'),
delay = require('./delay.js'),
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}`);
await delay(interval);
}
}
}