Created
November 20, 2018 10:06
-
-
Save vithonch/30874fcf033119bfff3a83739b9b1b69 to your computer and use it in GitHub Desktop.
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 | |
*/ | |
async function retry(fn, retriesLeft = 5, interval = 1000, exponential = false) { | |
try { | |
const val = await fn(); | |
return val; | |
} catch (error) { | |
if (retriesLeft) { | |
console.log(`Retrying in ${interval/1000} seconds... ${retriesLeft} retries left.`); | |
await new Promise(r => setTimeout(r, interval)); | |
return retry(fn, retriesLeft - 1, 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