Skip to content

Instantly share code, notes, and snippets.

@Hebilicious
Last active Nov 22, 2019
Embed
What would you like to do?
/**
* 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