umutm
umutm

Reputation: 2894

Using node-mysql in a function

I'm very new to nodejs and have a question.

Trying to create a function that will call the value of any field where I mention its ID from a table:

function getUserInfo (userID, dynamicField) {
    var query = connection.query('SELECT '+dynamicField+' from users WHERE userID = '+connection.escape(userID));
    query.on('result', function(row) {
        return(row.dynamicField);
    });
};
console.log(getUserInfo(8, userEmail)) //this should get me the userEmail value of the user with userID=8

However, I get "undefined". If I use console.log rather than return, it logs the value but this has no use as a function to be used inside other functions to get a value.

I will be glad if I can get help for modifying the function.

Upvotes: 6

Views: 7109

Answers (1)

srquinn
srquinn

Reputation: 10501

This is a common mistake amongst async/nodejs beginners. You have essentially wrapped an async function inside a sync function which breaks down the nature of node's event loop. The return expression needs to be replaced with a callback. See below:

// Method
function getUserInfo (userID, dynamicField, callback) {
    var query = connection.query('SELECT '+dynamicField+' from users WHERE userID = '+connection.escape(userID));
    query.on('result', function(row) {
        callback(null, row.dynamicField);
    });
};

// Implementation
getUserInfo(8, userEmail, function(err, result){
    console.log(err || result);
});

By convention, in Nodejs we always pass an error object first in the callback. In this case since there is no error to capture, we pass null in its place.

Upvotes: 12

Related Questions