raul
raul

Reputation: 1269

Return error to callback in Node.js

I have the following code:

User.findById(id, function(err, user) {
    //blah blah
});

The findById method is defined in the User module. It looks like this:

exports.findById = function(id,callback) {
    connection.query("SELECT * FROM usertable", function (err, rows, fields) {
            if (err) throw err;
            callback(rows);
        });
}

As the callback to the findById() method takes two parameters, namely, err and user, I'm wondering if I've defined the function in a proper way. Will the code work or do I have to pass the parameters to the callback in a different way?

Upvotes: 1

Views: 2089

Answers (1)

go-oleg
go-oleg

Reputation: 19480

If you get an error, you need to pass err to the callback, otherwise pass null as the first parameter and then your rows:

exports.findById = function(id,callback) {
    connection.query("SELECT * FROM usertable", function (err, rows, fields) {
            if (err) return callback( err );
            return callback(null, rows);
        });
}

Alternatively, since you aren't doing any transformations/modifications in your connection.query callback, you can just pass the findById callback straight through to connection.query:

exports.findById = function(id,callback) {
    connection.query("SELECT * FROM usertable", callback);
}

Upvotes: 2

Related Questions