查询节点js中mongodb中的第二次调用后的未定义值

时间:2014-01-06 11:00:55

标签: node.js

当我调用第二个查询时,我得到一个未定义的stateName值。我知道这是由于asynchronus的问题,我在google中搜索它以获得回调的概念,但不能。下面是代码。

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

1 个答案:

答案 0 :(得分:0)

console.log(statename)放入function(err, states)来电。像这样:

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

由于Node的异步性质,调用Mongo来查找状态名称,控制台立即打印了值(未定义),然后Mongo返回结果并可能设置stateName变量。