【问题标题】:Global Dictionary/Scope Issue全球词典/范围问题
【发布时间】:2014-04-09 21:03:50
【问题描述】:

我已经定义了一个全局字典,我想在 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 查询的回调。

标签: javascript mysql node.js


【解决方案1】:

您的代码在风格上是同步的,而它应该是异步的。 使用回调

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 2011-08-02
    • 1970-01-01
    • 2014-04-09
    • 2021-11-10
    • 1970-01-01
    • 2020-02-29
    相关资源
    最近更新 更多