Last active
March 1, 2018 09:20
-
-
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?
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
// 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))); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.