Javascript 全球词典/范围问题
我已经定义了一个全局字典,我想在MySQL连接块中添加它。问题是,一旦超出该块,字典就会显示为空。这感觉像是一个基本的范围问题,但添加到字典中的内容不会保持不变似乎很奇怪,不是吗 代码:Javascript 全球词典/范围问题,javascript,mysql,node.js,Javascript,Mysql,Node.js,我已经定义了一个全局字典,我想在MySQL连接块中添加它。问题是,一旦超出该块,字典就会显示为空。这感觉像是一个基本的范围问题,但添加到字典中的内容不会保持不变似乎很奇怪,不是吗 代码: 您的代码在样式上是同步的,而它应该是异步的使用回调 可能您的外部对象从未被填充,因为在您将对象打印到控制台时,mysql查询的回调从未被调用。 var express = require("express"); var http = require("http"); var mysql = require("m
您的代码在样式上是同步的,而它应该是异步的使用回调
可能您的外部对象从未被填充,因为在您将对象打印到控制台时,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........");
});
getBiz = function(onGetObjects) {
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;
onGetObjects(objects); // prints the objects
});
console.log(objects); //will definitely print {}
};
function onGetObjects(obj){
this.objects = obj;
console.log(objects) // should give you the correct objects
}
var app = express();
//pass in the callback
app.get("/", function(req, res) {
res.send(getBiz(onGetObjects));
});
var server = app.listen(8888, function() {
console.log("Listening........");
});