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.

umutm
  • 2,832
  • 4
  • 22
  • 22

1 Answers1

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.

srquinn
  • 10,134
  • 2
  • 48
  • 54
  • 3
    Yes, not-thinking the PHP (sync) way seems to take time. Thanks so much. – umutm Nov 14 '12 at 07:25
  • 1
    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.. – umutm Nov 14 '12 at 08:33
  • 1
    I just missed something simple (the brackets): callback(null, row[dynamicField]; – umutm Nov 14 '12 at 15:33
  • 2
    Took a while for me too (I came from PHP as well). So you figured it out? – srquinn Nov 14 '12 at 19:09
  • 2
    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. – umutm Nov 15 '12 at 11:26
  • Thank you very much, I was having a lot of difficulties working with functions within NODE, I also come from PHP, but I've been working with VUE for some time, but with NODE I'm catching on small traps that for a beginner is very difficult to discover. – Nebenzahl Mar 06 '22 at 20:42