Skip to content

Instantly share code, notes, and snippets.

@cowboy
Last active March 1, 2018 09:20
Show Gist options
  • Save cowboy/8417940 to your computer and use it in GitHub Desktop.
Save cowboy/8417940 to your computer and use it in GitHub Desktop.
Should Node.js have a helper method for this pattern? Does it already?
// Instead of lots of "if err, callback(err), else, callback(null, result)"
exports.doSomething = function(callback) {
var err, result;
// a bunch of code
if (err) {
callback(err);
} else {
callback(null, result);
}
};
// What if we just could do this?
var util = require('util');
exports.doSomethingElse = function(callback) {
var err, result;
// a bunch of code
util.hollaback(callback, err, result);
};
// Because util.hollaback looked something like:
exports.hollaback = function(callback, err, result) {
if (err) {
callback(err);
} else if (arguments.length === 3) {
// Make the most common case (one result argument) super fast.
callback(null, result);
} else {
// With the less common case (more arguments) being fast enough.
callback.apply(null, [null].concat([].slice.call(arguments, 2)));
}
};
@hectorcorrea
Copy link

What if we just always do callback(err, result) without the if statement? The callback should/would look for err first anyway and detect there is an error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment