0

app.js

MyDatabase = require("./mysql");
...
var availableRooms = mydb.checkRoomStatus();
console.log("Rooms " + availableRooms);
//undefined.

mysql.js

MyDatabase.prototype.checkRoomStatus = function() {
this.con.query('SELECT * FROM rooms WHERE status = "open" LIMIT 1',function(err,rows){
  if(err) throw err;

  console.log('Data received from Db:\n');
  console.log(rows); // results are coming here.
  return rows;
});

}

The first console.log is outputting "undefined" for availableRooms variable.
I think i should use a callback function for this kind of request.
But i dont know how to use it. When i search in internet, i dont find anyone using separate file for mysql to get callback results.

Mahesh
  • 1,503
  • 3
  • 22
  • 33
  • 1
    can you give the link to the exact node-mysql package that you are using? there are many, so, to avoid any confusion before people start answering. – Parthapratim Neog Mar 31 '16 at 06:25
  • @ParthapratimNeog I don't think this will help, as you can see the OP try to return result from callback.. – Ziki Mar 31 '16 at 06:28
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Ziki Mar 31 '16 at 06:31
  • npm install mysql - This is how i installed mysql package for node. Which one is stable? @Parthapratim Neog I think your solution is what i was searching for. I will try it out and let you know. – Mahesh Mar 31 '16 at 06:42
  • 1
    Else you can use promise too!! – vkstack Mar 31 '16 at 06:56

1 Answers1

3

You need to return callback(rows) to return your rows and you need to catch it in your callback. I hope it's clear. Try this out, and see if it works.

change your mysql code to

MyDatabase.prototype.checkRoomStatus = function(callback) {
this.con.query('SELECT * FROM rooms WHERE status = "open" LIMIT 1',function(err,rows){
  if(err) throw err;

  console.log('Data received from Db:\n');
  console.log(rows); // results are coming here.
  return callback(rows);
});

Now in app.js

MyDatabase = require("./mysql");
...
mydb.checkRoomStatus(function(res){
    var availableRooms = res;
    console.log("Rooms " + availableRooms);
});
Parthapratim Neog
  • 4,352
  • 6
  • 43
  • 79