编辑:我可以看到另一个问题可能是处理同样的问题,但是我无法理解如何将他的函数foo(){..}的解决方案应用于我的具体问题(不是至少因为他是jQuery)。如果有人可以在这里解释,那么我将此问题标记为重复。
在自定义类中,可以访问该值,但在主代码块中,返回值是“未定义的”'。由于数据库连接,这是一些同步问题吗?我可以以某种方式在主index.js调用函数中访问该值吗?
index.js:
"use strict"
const PORT = 3000;
const express = require("express");
const server = express();
const http = require("http").Server(server);
const path = require("path");
const io = require("socket.io")(http);
const DB = require("./ofcModules/DB");
http.listen(PORT, function() {
console.log("server listening on port " + PORT);
});
//serve index.html (and CSS/JS) when receives a request
server.use(express.static(path.join(__dirname + "/public")));
server.use(express.static(__dirname + "/public/css"));
server.use(express.static(__dirname + "/public/js"));
//*********Connect to Database************************
var mDB = new DB();
var mTblID;
mDB.connect()
mTblID = mDB.newTable();
console.log("mTblID: " + mTblID);
自定义数据库类:
"use strict"
const mysql = require("mysql");
class DB{
constructor() {
this.conn = mysql.createConnection({
host : 'localhost',
user : "hfghr",
password: "dhrjtyjnm",
database: "yiluilrt"
});
}
connect() {
this.conn.connect(function(err) {
if (err) {
console.error("error connecting: " + err.stack);
//throw err;
return;
}
console.log("connected to DB");
return this.conn;
});
}
newTable() {
this.conn.query("INSERT INTO tbltables (notes) VALUES ('table opened')", function(err, result){
if (err) {
console.error("error getting table ID from mysql: " + err.stack);
throw err;
return;
}
console.log("playing table created via DB. ID: " + result.insertId);
return result.insertId;
});
}
}
module.exports = DB
这是服务器控制台输出:
mTblID: undefined
server listening on port 3000
connected to DB
playing table created via DB. ID: 18
答案 0 :(得分:2)
你的newTable函数实际上并没有返回任何值。由于mysql.query是异步的,因此您需要提供回调。解决方案是将函数传递给newTable,它将在mysql.query回调中执行。这是一个粗略的例子:
//*********Connect to Database************************
var mDB = new DB();
mDB.connect()
mDB.newTable(function (mTblID) {
console.log("mTblID: " + mTblID);
});
这是newTable的实现
newTable(callback) {
this.conn.query("INSERT INTO tbltables (notes) VALUES ('table opened')", function(err, result){
if (err) {
console.error("error getting table ID from mysql: " + err.stack);
throw err;
return;
}
console.log("playing table created via DB. ID: " + result.insertId);
callback(result.insertId);
});
}