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')) |
Renamed fn
to promiseGenerator
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice!
The only thing I'd change would be renaming the
fn
to something that implies that the function returns a promise, but I'm not sure I can think of something that would be concise....fnThatReturnsPromise
(too long)I guess some jsdoc would remedy that.
Are you adding this to the v3 API SDK?