Last active
September 21, 2017 19:47
-
-
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
This file contains 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
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