Last active
October 4, 2018 05:42
-
-
Save scwood/4ffab11dbf88bbeda1b0ceb7429a26b0 to your computer and use it in GitHub Desktop.
Exponential backoff retry logic for a function that returns a Promise
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 a function that returns a promise a given number of times and backs | |
* off each attempt exponentially. | |
* | |
* @param {Function} promiseGenerator The function to retry. | |
* @param {number} [attempts=5] Number of attempts to make. | |
* @param {number} [delay=1000] Initial delay between attempts in ms. | |
* @return {Promise} | |
*/ | |
function attemptWithRetry(promiseGenerator, attempts = 5, delay = 100) { | |
return new Promise((resolve, reject) => { | |
promiseGenerator() | |
.then(resolve) | |
.catch((error) => { | |
if (attempts > 1) { | |
setTimeout(() => { | |
resolve( | |
attemptWithRetry(promiseGenerator, attempts - 1, delay * 2) | |
); | |
}, delay); | |
} else { | |
reject(error); | |
} | |
}); | |
}); | |
} | |
// Example: | |
// | |
// function coinFlip () { | |
// return Math.floor(Math.random() * 2) === 0 | |
// } | |
// | |
// function failHalfTheTime () { | |
// return new Promise((resolve, reject) => { | |
// coinFlip() ? resolve() : reject() | |
// }) | |
// } | |
// | |
// attemptWithRetry(failHalfTheTime) | |
// .then(() => console.log('success')) | |
// .catch(() => console.error('error')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Renamed
fn
topromiseGenerator
.