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.

5
  • 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. Commented Mar 31, 2016 at 6:25
  • @ParthapratimNeog I don't think this will help, as you can see the OP try to return result from callback.. Commented Mar 31, 2016 at 6:28
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Mar 31, 2016 at 6: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. Commented Mar 31, 2016 at 6:42
  • 1
    Else you can use promise too!! Commented Mar 31, 2016 at 6:56

1 Answer 1

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

1 Comment

I'm trying to do the same thing, but in mysql.js, it says MyDatabase is not defined, where exactly is it created? and where did mydb object come?

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.