Skip to content

Instantly share code, notes, and snippets.

@Hebilicious
Last active November 22, 2019 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Hebilicious/528a910978b251e08f96eac7ea597274 to your computer and use it in GitHub Desktop.
Save Hebilicious/528a910978b251e08f96eac7ea597274 to your computer and use it in GitHub Desktop.
/**
* Retries the given function until it succeeds given a number of retries and an interval between them. They are set
* by default to retry 5 times with 1sec in between. There's also a flag to make the cooldown time exponential
* @param {Function} fn - Returns a promise
* @param {Number} retriesLeft - Number of retries. If -1 will keep retrying
* @param {Number} interval - Millis between retries. If exponential set to true will be doubled each retry
* @param {Boolean} exponential - Flag for exponential back-off mode
* @return {Promise<*>}
*/
const retryPromise = ({fn, retriesLeft = 5, interval = 1000, exponential = false}) => {
try {
return await fn();
} catch (error) {
if (retriesLeft) {
await new Promise(resolve => setTimeout(resolve, interval));
return retry({fn, retriesLeft: retriesLeft - 1, interval: exponential ? interval * 2 : interval, exponential});
} else throw new Error('Max retries reached');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment