Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS callback with null as first argument

Tags:

node.js

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);
    }
}
like image 878
estrar Avatar asked Mar 19 '14 21:03

estrar


People also ask

Can callback be NULL?

No, the callback cannot be NULL.

What is the first argument passed to a callback handler in Nodejs?

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).

What is the first argument at the asynchronous callback?

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.

Why does node js prefer error first callback?

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.


1 Answers

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.

like image 68
Explosion Pills Avatar answered Nov 14 '22 08:11

Explosion Pills