全球词典/范围问题

时间:2014-04-09 21:03:51

标签: javascript mysql node.js

我已经定义了一个全局字典,我想在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........");
});

1 个答案:

答案 0 :(得分:0)

当代码异步时,代码在样式上是同步的。 使用回调

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........");
});