0

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..

5
  • Your question isn't very clear. Besides, I don't know how we're supposed to help you without knowing what connection is. Commented Nov 28, 2013 at 6:53
  • K wait i will update my question.. Commented Nov 28, 2013 at 6:54
  • My guess: connection.query is part of e.g. node-mysql or another sql module. So most likely it is an async call, so the callback function is not called at the time where you do the return result; Commented Nov 28, 2013 at 6:56
  • Thanks @t.niese ..What i have to modify to achieve this.. Commented Nov 28, 2013 at 6:57
  • @Subburaj look at the answer of Joachim Pileborg Commented Nov 28, 2013 at 6:57

2 Answers 2

2

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);
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.