Last active
August 29, 2015 14:09
-
-
Save briansorahan/6d43528bb380df7644e7 to your computer and use it in GitHub Desktop.
callback wrapper for node.js
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
/** | |
* Wrap a node callback so that it doesn't have to do error-checking. | |
* Returns a function that checks for an error as the first argument. | |
* If the error is truthy and you provided an error handler, it passes | |
* the error to this function. Otherwise it calls cb with the error. | |
* If there was no error and you provided an error handler, it | |
* only passes the remaining arguments to cb. Otherwise it passes | |
* null as the first argument (the error). | |
* | |
* @param {Function} cb - function(err, ...) or function(...) | |
* @param {Function} [errorHandler] - Optional function(err) | |
*/ | |
function cbwrap(cb, errorHandler) { | |
if (!_.isFunction(cb)) { | |
throw new TypeError('cbwrap expects a function argument'); | |
} | |
return function(err) { | |
if (err) { | |
if (typeof errorHandler === 'function') { | |
errorHandler(err); | |
} else { | |
cb(err); | |
} | |
} else { | |
var args = Array.prototype.slice.call(arguments, 1); | |
if (typeof errorHandler === 'function') { | |
// if an error handler was provided, cb should not care | |
// about the error | |
cb.apply(cb, args); | |
} else { | |
cb.apply(cb, [null].concat(args)); | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment