0

node-mysql query returning undefined.

Here is my code:

Hash.prototype.GetHash = function()
    {
        var test;
        var connection = this.config.CreateConnection();
        connection.connect(function(err){
           if (err)
               throw err;
           else
           {
               var query = "SELECT hash FROM test WHERE id = 1";
               connection.query(query, function(err, rows, result){
                  if (err)
                      throw err;
                  else
                  {
                      test = rows[0].hash;
                      console.log(test);
                  }
               });
               connection.end(function(err){
                   if (err)
                       throw err;
               });
           }
        });
        return test;
    }

console.log will give me right result 1a2b3c4d. So. When I call this method to main method:

    var h = hash.GetHash();
    console.log(h);

Console give me result undefined.

So I tried to cast, retype, create a new object from string class: this object test like:

var test = '';
var test = new String;
var test = new String(rows[0].hash);

And without succes :\ Can anyone help me with this problem? Thanks a lot guys!

1 Answer 1

4

Node.js is asynchronous, your code Hash.prototype.GetHash = function() {} will not work as it returns the value immediately when called, but has not executed it as yet. So when you print test, it gives undefined.

To use your test that your function computes and you are trying to return, you must use callback with test as its argument to use it, after your function completes. You will have to do some changes in your function.

Hash.prototype.GetHash = function(callback){
//pass callback in arguments if you want it to be provided when calling
...  //compute test
//return test; Dont do return, do callback
callback(test);
}

//Your definition of callback should be
callback = function(h){
console.log(h);
}

See the tutorials to learn more:

  1. http://docs.nodejitsu.com/articles/getting-started/control-flow/how-to-write-asynchronous-code
  2. http://howtonode.org/control-flow
  3. http://howtonode.org/control-flow-part-ii
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.