Skip to content

Instantly share code, notes, and snippets.

@scwood
Last active October 4, 2018 05:42
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scwood/4ffab11dbf88bbeda1b0ceb7429a26b0 to your computer and use it in GitHub Desktop.
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'))
@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