【发布时间】:2017-08-30 10:38:17
【问题描述】:
编辑:我可以看到另一个问题可能正在处理同样的问题,但我不明白如何将他的函数 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
【问题讨论】:
-
this.conn.query同步吗? -
我不确定。它来自标准 mysql node.js 模块。
-
mysql.query 函数是异步的。
标签: javascript mysql node.js class ecmascript-6