Last active
December 31, 2015 04:19
-
-
Save martin-wintz/7933420 to your computer and use it in GitHub Desktop.
asyncWithRetry
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
// Takes an asynchronous function func and returns an asynchronous function decoratedFunc that | |
// calls func until it either runs out of tries or doesn't pass an error into the callback | |
// makes numRetries available as the last argument in func | |
var asyncWithRetry = function (func, numRetries) { | |
var decoratedFunc = function () { | |
var currentRetry, args, callback, newCallback, callbackArgs, err; | |
currentRetry = 0; | |
args = Array.prototype.slice.call(arguments, 0); | |
// Replace the callback with one that has retry logic | |
callback = args[args.length - 1]; | |
newCallback = function () { | |
currentRetry += 1; | |
callbackArgs = Array.prototype.slice.call(arguments, 0); | |
err = callbackArgs[0]; | |
if (err && currentRetry < numRetries) { | |
args.splice(args.length - 1, 1, currentRetry); | |
func.apply(null, args); | |
} else { | |
callback.apply(null, callbackArgs); | |
} | |
}; | |
args.splice(args.length - 1, 1, newCallback, currentRetry); | |
func.apply(null, args); | |
}; | |
return decoratedFunc; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment