0
當我調用第二個查詢時,我得到了stateName的未定義值。我知道這是由於異步問題,我已經在谷歌搜索它獲得回調的概念,但不能。下面是代碼。在節點js中查詢mongo數據庫中的第二個調用後未定義的值
exports.getEmployee = function(req, res) {
var jsonArray = [];
var jsonString;
var success = true;
if(success == true){
mongooseDBObject.var_employee.find(jsonString, function(err, doc_employee){
if(err == null) {
if(doc_employee_travel == "") {
res.status(404);
res.json({result: "Employee record not found."});
} else {
doc_employee.forEach(function(docEmployee){
mongooseDBObject.var_states.find({stateID: docEmployee.statename},function(err, states){
states.forEach(function(statesLoop){
stateName = statesLoop.stateName;
});
});
console.log(stateName); //showing undefined.
});
res.status(200);
res.json(jsonArray);
}
} else {
res.json({error: err});
}
});
}
}
你想用'stateName'做什麼?對'var_states.find'的調用是異步的,所以函數立即返回,因此變量沒有被定義。 – WiredPrairie