Skip to content

Instantly share code, notes, and snippets.

@pianosnake
Last active September 21, 2017 19:47
Show Gist options
  • Save pianosnake/89983e908e4fb8fde52d3349e8e4d78f to your computer and use it in GitHub Desktop.
Save pianosnake/89983e908e4fb8fde52d3349e8e4d78f to your computer and use it in GitHub Desktop.
retry a Request repeatedly until it succeeds or the try limit is reached
function insistentRequest(request, tryLimit){
if(!tryLimit) return Promise.reject('tryLimit must be above 0');
let tries = 0;
return new Promise(function(resolve, reject){
//create a generator object that repeatedly 'yields' the same promise until it succeeds or the try limit is reached
const genObj = function* gen(){
while(1){
yield request()
.then(resolve)
.catch(e => {
tries ++;
if(tries === tryLimit) return reject(e);
else return genObj.next();
});
}
}();
genObj.next();
});
}
//example
insistentRequest(() => load('blah.jpg'), 4)
.then(response => ...)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment