Reputation: 141
I am trying to write a database manager module in node.js for some of the common queries I am going to use in a server app. I want to test the module. However, my code does not connect to the database before I do the queries. How can I arrange my code in such way, it connects to db before the queries, not after them?
var mysql = require('mysql');
var conn = mysql.createConnection(
{
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb'
});
conn.connect(function(error)
{
if ( error) throw error;
console.log('->connected to database');
});
// user as json
getUserData = function(username)
{
conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username +
'\"' , function (error, result, fields)
{
if (error) throw error;
return result;
});
}
console.log('result->' + JSON.stringify(getUserData('eness')));
conn.end();
result->undefined
->connected to database
Upvotes: 2
Views: 69
Reputation: 3614
Your getUserData()
has nothing to return. Returning result
from the query's callback function does not make it the return value of getUserData()
as callback is executed asynchronously.
You can't return from an asynchronous function call inside a synchronous function.
If you move the console.log()
line into the callback, you will see the correct output:
getUserData = function(username) {
conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username + '\"' , function (error, result, fields) {
if (error) throw error;
console.log('result->' + JSON.stringify(result));
});
}
getUserData('eness');
conn.end();
If you don't want to put the logic in the query's callback (separate query and business logic):
getUserData = function(username, cb) {
conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username + '\"' , function (error, result, fields) {
if (error) throw error;
cb(result)
});
}
getUserData('eness', function(result) {
console.log('result->' + JSON.stringify(result));
});
conn.end();
Welcome to callback hell :) Now consider using Promise.
Upvotes: 2
Reputation: 3266
This is happening because of the async nature of node.js , the code after conn.connect
will not wait for that connection to complete to execute getUserData
, therefore since the getUserData
operation is not waiting for the connection to happen before executing you're probably having this error. Try the following to fix this for only testing purposes. And if youre using the getUserData
function connected to a REST endpoint this will not occur since connection happens when the nodejs app is starting.
conn.connect(function(error)
{
if ( error) throw error;
else console.log('result->' + JSON.stringify(getUserData('eness')));
console.log('->connected to database');
});
function getUserData(username)
{
conn.query('SELECT * FROM USERS WHERE USERNAME = \"' + username +
'\"' , function (error, result, fields)
{
if (error) throw error;
return result;
});
}
conn.end();
Upvotes: 1