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-07-27 15:28:05 +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")
|
2023-07-10 21:40:13 +02:00
|
|
|
* @param {string} args.retryUntilFailure - Retries until the function fails.
|
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(
|
2023-07-10 21:40:13 +02:00
|
|
|
{
|
|
|
|
retries,
|
|
|
|
delay = 0,
|
|
|
|
rejectionMessage = 'Retry limit reached',
|
|
|
|
retryUntilFailure = false,
|
|
|
|
},
|
2021-09-01 18:40:40 +02:00
|
|
|
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();
|
2023-07-10 21:40:13 +02:00
|
|
|
if (!retryUntilFailure) {
|
|
|
|
return;
|
|
|
|
}
|
2021-06-15 19:51:25 +02:00
|
|
|
} catch (error) {
|
|
|
|
console.error(error);
|
2023-07-10 21:40:13 +02:00
|
|
|
if (retryUntilFailure) {
|
|
|
|
return;
|
|
|
|
}
|
2021-06-15 19:51:25 +02:00
|
|
|
} 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 };
|