2014-04-09 111 views
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........"); 
}); 
+0

也許你的外部對象永遠不會填充,因爲你的MySQL查詢回調從來沒有得到你打印出來的對象到控制檯時調用。 – shanks

回答

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