1
我定義了一個全局字典,我想在它的一個MySQL連接塊中添加它。問題是,一旦在該塊之外,字典就顯示爲空。這感覺就像一個基本的範圍問題,但似乎很奇怪,添加到字典中的東西不會保持放置,不是嗎?全球字典/範圍問題
代碼:
var express = require("express");
var http = require("http");
var mysql = require("mysql");
objects = {};
getBiz = function() {
var connection = mysql.createConnection({
host:"localhost",
user:"APIUser",
password:"password"
});
connection.query("USE biz");
var bizQuery = "SELECT * FROM biz";
var bizObjects = [];
connection.query(bizQuery, function(err, bizRows) {
if (err) {
throw err;
} else {
for (bizRow in bizRows) {
var bizObject = {};
bizObject['id'] = bizRows[bizRow]['id'];
bizObject['biz_name'] = bizRows[bizRow]['biz_name'];
bizObjects.push(bizObject);
}
}
objects['biz'] = bizObjects;
console.log(objects); // prints the objects
});
console.log(objects); // prints {}
};
var app = express();
app.get("/", function(req, res) {
res.send(getBiz());
});
var server = app.listen(8888, function() {
console.log("Listening........");
});
也許你的外部對象永遠不會填充,因爲你的MySQL查詢回調從來沒有得到你打印出來的對象到控制檯時調用。 – shanks