节点 js - 节点 mysql - 结果未定义

node js - Node mysql - Result is undefined

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 的单独文件来获取回调结果。

您需要 return callback(rows) 到 return 您的行,并且您需要在 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);
});