Skip to content

Instantly share code, notes, and snippets.

@scwood
Last active October 4, 2018 05:42
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save scwood/4ffab11dbf88bbeda1b0ceb7429a26b0 to your computer and use it in GitHub Desktop.
Exponential backoff retry logic for a function that returns a Promise
/**
* 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'))
@kyleguate
Copy link

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?

@scwood
Copy link
Author

scwood commented Nov 13, 2017

Renamed fn to promiseGenerator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment