Using node-mysql in a function

I am very new to nodejs and ask a question.

Trying to create a function that will call the value of any field where I mention its identifier from the 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 instead of returning, it registers the value, but it is not used as a function that will be used inside other functions to get the value.

I will be glad if I can get help to change the function.

+3
source share
1 answer

This is a common mistake among async / nodejs newbies. You essentially wrapped an asynchronous function inside a synchronization function that destroys the nature of the node event loop. The returned expression must be replaced by 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 the error object first in the callback. In this case, since there is no error to capture, we pass null to its place.

+8
source

All Articles