Subburaj
Subburaj

Reputation: 5192

Function in node.js

In my node application i am using function.But i am getting the result of that function:

My code:

var connection = mysql.createConnection({
  host     : 'localhost',  
  user     : 'xxxx',
  password : 'xxxxx',
  database : 'xxxxxxx',
  debug : true,
})
connection.connect(function(err) {
    if ( !err ) {
        console.log("Connected to MySQL");
    } else if ( err ) {
        console.log(err);
    }
});

 if(level5 == undefined)
{
   var result1=querylevel5();
   console.log("vvvvvvvvv="+result1)
   res.writeHead(200, { 'Content-Type': 'application/json'});
   res.end(JSON.stringify(result1,null,"\n"));
}

My function:

    function querylevel5()
    {
      var result;    
      connection.query("select * from levels ", function(err, row1, fields) {
        result= row1;
        /*res.writeHead(200, { 'Content-Type': 'application/json'});
        res.end(JSON.stringify(row1,null,"\n"));*/
      });
      return result;
    }

I want to get the row1 result ,in my calling function..But its printing "undefined"..I am new to this node.js..So please help me to solve this..Thanks in advance..

Upvotes: 0

Views: 80

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409442

Most likely the problem is that the function querylevel5 returns immediately before result. You have to do like most any other node.js framework does, like for example the connection.query function, namely use callbacks:

if(level5 == undefined) {
    querylevel5(function(result) {
        console.log("vvvvvvvvv="+result)
        res.writeHead(200, { 'Content-Type': 'application/json'});
        res.end(JSON.stringify(result,null,"\n"));
    });
}

And

function querylevel5(callback) {
    connection.query("select * from levels ", function(err, row1, fields) {
        callback(row1);
    });
}

Upvotes: 2

Bill Ticehurst
Bill Ticehurst

Reputation: 1868

The problem is the result is delivered in a callback (i.e. asynchronously), but you are calling the method synchronously and printing the result - so the result hasn't actually been returned by the time you try to print it.

Upvotes: 0

Related Questions