26 lines
798 B
JavaScript
26 lines
798 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}`);
|
|
await timers.setTimeout(interval);
|
|
}
|
|
}
|
|
}
|