Files
cloudron-box/src/promise-retry.js
T

26 lines
780 B
JavaScript
Raw Normal View History

2021-05-06 22:29:34 -07:00
'use strict';
exports = module.exports = promiseRetry;
const assert = require('assert'),
2022-04-15 07:52:35 -05:00
delay = require('./delay.js'),
2021-05-06 22:29:34 -07:00
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 {
2021-12-08 10:19:16 -08:00
return await asyncFunction(i+1 /* attempt */);
2021-05-06 22:29:34 -07:00
} catch (error) {
if (i === times - 1) throw error;
if (options.retry && !options.retry(error)) throw error; // no more retry
2021-12-07 11:14:24 -08:00
if (options.debug) options.debug(`Attempt ${i+1} failed. Will retry: ${error.message}`);
2021-05-06 22:29:34 -07:00
await delay(interval);
}
}
}