Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using node-mysql in a function

Tags:

node.js

mysql

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.

like image 581
umutm Avatar asked Nov 13 '12 16:11

umutm


People also ask

Can you use node with MySQL?

Once you have MySQL up and running on your computer, you can access it by using Node. js. To access a MySQL database with Node. js, you need a MySQL driver.

Can you use node with SQL?

You can connect to a SQL Database using Node. js on Windows, Linux, or macOS.


1 Answers

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.

like image 92
srquinn Avatar answered Oct 01 '22 03:10

srquinn