merstik
merstik

Reputation: 101

Trying to return a row from MySql using a function inside a route and won't get a response

So i'm trying to use a function that returns a row from a mySql database inside my route here:

.get('/users', function (req, res){
    res.send(userInfo(req.user.id));
})

Here is the function:

function userInfo(id){
    colDB.query('SELECT username FROM users WHERE id = ?', [id], function(err, rows){
        if (err)
            return {Error: defErrorMsg};
        else
            return rows;
})}

I'm fairly new to node and I can't figure out why isn't this working. Please help :(

Upvotes: 2

Views: 44

Answers (1)

Ash
Ash

Reputation: 6783

I think this is to do with the callback nature of node. You are returning the value before it exists (treating async code like it's synchronous). Try the following:

function userInfo(id, callback){
    colDB.query('SELECT username FROM users WHERE id = ?', [id], function(err, rows){
        if (err)
            callback(err, null);
        else
            callback(null, rows);
})}

And then change the route to look like this:

.get('/users', function (req, res){
    userInfo(req.user.id, function(err, user){
      if(err) return res.send(err)
      res.send(user)
    });
})

Upvotes: 2

Related Questions