在node.js中使用async时出错

时间:2013-05-04 17:33:04

标签: javascript node.js asynchronous express

我正在尝试使用express框架和node.js编写restapi。我面临一个错误,我无法找出根本原因。我在尝试执行代码时收到以下错误:

TypeError: Cannot read property 'node_type' of undefined其中'node_type'是来自函数的值

var GdbProcess = require('../../dao/gdb/processnds')
var mongo = require('mongodb');
var async = require('async');

exports.executeService =  function(req,res){
//Make the process object to query
var manualProcessQuery = new Object();
manualProcessQuery.index = req.params.processmap;
manualProcessQuery.key = "pid";
manualProcessQuery.value = req.params.pid;
manualProcessQuery.event = req.params.event;

var tempDataNodeToExecute = new Object();
//This function returns  an object (dataNodeToExecute) to execute
GdbProcess.getParametersbyNode(manualProcessQuery,function(err,dataNodeToExecute){
    if(err) res.send(err);
    tempDataNodeToExecute = dataNodeToExecute;
    var isSystem = false;
    if (tempDataNodeToExecute.node_type =="system"){
        isSystem = true;
    }

    var count = 0;

    async.whilst(
        function () { return isSystem },
        function (callback) {
            //execute the function
            executeSystem(dataNodeToExecute,function(err,executionStatus){
                if (err) callback(err);
                count++;
                if(executionStatus=="completed"){
                    manualProcessQuery.value = tempDataNodeToExecute.pid;
                    manualProcessQuery.event = "completed";
                         GdbProcess.getParametersbyNode(manualProcessQuery,function(err,dataNodeToExecute2){
                        if(err) callback(err);
                        tempDataNodeToExecute = dataNodeToExecute2;
                        if (tempDataNodeToExecute.node_type == "manual"){
                            isSystem = false;
                        }

                    });

                    callback();
                }
            });
        },
        function (err) {
            if(err) res.send(err);
            res.send("success");
        }
    );
});

}



var executeManual = function(prosNodeToExecute,callback){
//do something
callback (null);
}

var executeSystem = function(prosNodeToExecute,callback){
//do something
callback(null,"completed");
}

当我调试代码时,我清楚地看到node_type可用。有人可以帮我找到根本问题吗?

1 个答案:

答案 0 :(得分:0)

删除新对象tempDataNodeToExecute并使用dataNodeToExecute而不是它,在使用其属性之前检查对象的null是一个好习惯,这样程序就不会崩溃。