6

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.

1 Answer 1

12

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Yes, not-thinking the PHP (sync) way seems to take time. Thanks so much.
although I have marked it as the "accepted answer", after trying the code, I'm still getting "undefined". I just changed this line to getUserInfo(8, userEmail, function(err, result){ to getUserInfo(8, 'userEmail', function(err, result){ but no luck..
I just missed something simple (the brackets): callback(null, row[dynamicField];
Took a while for me too (I came from PHP as well). So you figured it out?
Yes, I guess so. Actually, it works without adding the callback function as (that's why I think) query.on('result' is already a callback. I tried many things and realized that I have to think everything asyn, not only functions and shape all the code in that way.. :) Thanks much again.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.