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;
});
}
第一个console.log正在为availableRooms变量输出“undefined” 我想我应该使用回调函数来处理这种请求 但我不知道如何使用它。当我在互联网上搜索时,我找不到任何人使用mysql的单独文件来获得回调结果。
答案 0 :(得分:3)
您需要return callback(rows)
返回行,并且需要在callback
中捕获它们。我希望它清楚。试试这个,看看它是否有效。
将您的mysql代码更改为
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);
});
现在在app.js
MyDatabase = require("./mysql");
...
mydb.checkRoomStatus(function(res){
var availableRooms = res;
console.log("Rooms " + availableRooms);
});