Skip to content

Instantly share code, notes, and snippets.

@tweinfeld
Last active April 5, 2017 02:23
Show Gist options
  • Save tweinfeld/4b12281766db702c4d52a0d484f01d1f to your computer and use it in GitHub Desktop.
Save tweinfeld/4b12281766db702c4d52a0d484f01d1f to your computer and use it in GitHub Desktop.
Repeat a promise-generating function until resolution
function repeatPromise(func, attempts = 10, delay = 1000) {
let attemptNumber = 0;
return (function internalTry() {
attemptNumber++;
if (attemptNumber > attempts) {
return Promise.reject('Number of attempts exceeded');
} else {
return func().catch(() => new Promise((resolve) => setTimeout(resolve, delay)).then(internalTry));
}
})();
};
// Usage
repeatPromise(()=>{ [... function that returns a promise ...] }, 15, 1000)
.then(console.log)
.catch(console.warn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment