Forked from briancavalier/simple-promise-retry.js
Last active
April 27, 2020 09:29
-
-
Save hemanthkodandarama/23859cddc04075717e83fb68870b2d25 to your computer and use it in GitHub Desktop.
A few general patterns for retries using promises
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 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 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 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