Skip to content

Instantly share code, notes, and snippets.

@martin-wintz
Last active December 31, 2015 04:19
Show Gist options
  • Save martin-wintz/7933420 to your computer and use it in GitHub Desktop.
Save martin-wintz/7933420 to your computer and use it in GitHub Desktop.
asyncWithRetry
// 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