Created
February 24, 2011 18:35
-
Star
(223)
You must be signed in to star a gist -
Fork
(34)
You must be signed in to fork a gist
-
-
Save briancavalier/842626 to your computer and use it in GitHub Desktop.
A few general patterns for retries using promises
This file contains hidden or 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 keepTrying(otherArgs, promise) { | |
promise = promise||new Promise(); | |
// try doing the important thing | |
if(success) { | |
promise.resolve(result); | |
} else { | |
setTimeout(function() { | |
keepTrying(otherArgs, promise); | |
}, retryInterval); | |
} | |
} |
This file contains hidden or 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 keepTrying(otherArgs, retryInterval, promise) { | |
promise = promise||new Promise(); | |
// try doing the important thing | |
if(success) { | |
promise.resolve(result); | |
} else { | |
setTimeout(function() { | |
// Try again with incremental backoff, 2 can be | |
// anything you want. You could even pass it in. | |
// Cap max retry interval, which probably makes sense | |
// in most cases. | |
keepTrying(otherArgs, Math.min(maxRetryInterval, retryInterval * 2), promise); | |
}, retryInterval); | |
} | |
} |
This file contains hidden or 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 tryAtMost(otherArgs, maxRetries, promise) { | |
promise = promise||new Promise(); | |
// try doing the important thing | |
if(success) { | |
promise.resolve(result); | |
} else if (maxRetries > 0) { | |
// Try again if we haven't reached maxRetries yet | |
setTimeout(function() { | |
tryAtMost(otherArgs, maxRetries - 1, promise); | |
}, retryInterval); | |
} else { | |
promise.reject(error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An alternative, with a bit more flexibility.