2021-06-15 19:51:25 +02:00
|
|
|
/**
|
2021-09-01 18:40:40 +02:00
|
|
|
* Re-runs the given function until it returns a resolved promise or the number
|
|
|
|
* of retries is exceeded, whichever comes first (with an optional delay in
|
|
|
|
* between retries).
|
2021-06-15 19:51:25 +02:00
|
|
|
*
|
2022-08-24 20:57:47 +02:00
|
|
|
* @param {object} args - A set of arguments and options.
|
2021-09-01 18:40:40 +02:00
|
|
|
* @param {number} args.retries - The maximum number of times to re-run the
|
|
|
|
* function on failure.
|
|
|
|
* @param {number} args.delay - The amount of time (in milliseconds) to wait in
|
|
|
|
* between retries. (Default: 0)
|
|
|
|
* @param {string} args.rejectionMessage - The message for the rejected promise
|
|
|
|
* this function will return in the event of failure. (Default: "Retry limit
|
|
|
|
* reached")
|
2022-01-07 16:57:33 +01:00
|
|
|
* @param {Function} functionToRetry - The function that is run and tested for
|
2021-09-01 18:40:40 +02:00
|
|
|
* failure.
|
|
|
|
* @returns {Promise<null | Error>} a promise that either resolves to null if
|
|
|
|
* the function is successful or is rejected with rejectionMessage otherwise.
|
2021-06-15 19:51:25 +02:00
|
|
|
*/
|
2021-09-01 18:40:40 +02:00
|
|
|
async function retry(
|
|
|
|
{ retries, delay = 0, rejectionMessage = 'Retry limit reached' },
|
|
|
|
functionToRetry,
|
|
|
|
) {
|
2021-06-15 19:51:25 +02:00
|
|
|
let attempts = 0;
|
|
|
|
while (attempts <= retries) {
|
2021-09-01 18:40:40 +02:00
|
|
|
if (attempts > 0 && delay > 0) {
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
|
|
}
|
|
|
|
|
2021-06-15 19:51:25 +02:00
|
|
|
try {
|
|
|
|
await functionToRetry();
|
|
|
|
return;
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
|
|
|
} finally {
|
|
|
|
attempts += 1;
|
|
|
|
}
|
|
|
|
}
|
2021-09-01 18:40:40 +02:00
|
|
|
|
|
|
|
throw new Error(rejectionMessage);
|
2021-06-15 19:51:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = { retry };
|