I've just started out with NodeJS and trying to get the hang of callbacks.
Today I've seen null passed by as the first argument to the callback in many examples. Please help me understand why it's there and why I need it.
Example 1
UserSchema.methods.comparePassword = function(pwd, callback) {
bcrypt.compare(pwd, this.password, function(err, isMatch) {
if (err) return callback(err);
callback(null, isMatch);
});
};
Example 2
example.method = {
foo: function(callback){
setTimeout(function(){
callback(null, 'foo');
}, 100);
}
}
No, the callback cannot be NULL.
The first argument of the callback handler should be the error and the second argument can be the result of the operation. While calling the callback function if there is an error we can call it like callback(err) otherwise we can call it like callback(null, result).
The first argument in the function is reserved for the error object. If any error has occurred during the execution of the function, it will be returned by the first argument. The second argument of the callback function is reserved for any successful data returned by the function.
Error-first callback in Node. js is a function that returns an error object whenever any successful data is returned by the function. The first argument is reserved for the error object by the function. This error object is returned by the first argument whenever any error occurs during the execution of the function.
By convention in node, the first argument to a callback is usually used to indicate an error. If it's something other than null
, the operation was unsuccessful for some reason -- probably something that the callee cannot recover from but that the caller can recover from. Any other arguments after the first are used as return values from the operation (success messages, retrieval, etc.)
This is purely by convention and there is nothing to stop you from writing a function that passes success as the first argument to a callback. If you plan to write a library that is adopted by other node users, you will probably want to stick with convention unless you have a very good reason not to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With