Last active
November 22, 2019 20:16
-
-
Save Hebilicious/528a910978b251e08f96eac7ea597274 to your computer and use it in GitHub Desktop.
Retry promises (https://gist.github.com/briancavalier/842626)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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