2014-01-06 54 views
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}); 
     } 
    }); 
} 
} 
+0

你想用'stateName'做什麼?對'var_states.find'的調用是異步的,所以函數立即返回,因此變量沒有被定義。 – WiredPrairie

回答

0

console.log(statename)放在function(err, states)的調用中。就像這樣:

   function(err, states){ 
        states.forEach(function(statesLoop){ 
         stateName = statesLoop.stateName; 
        }); 
        console.log(stateName); //Should show something useful 
       }); 

由於節點的異步性質,蒙戈調用找到狀態的名字叫,控制檯立即輸出的值(這是不確定的),然後蒙戈返回的結果想必設置變量stateName

相關問題