【问题标题】:nodejs : TypeError: callback is not a functionnodejs:TypeError:回调不是函数
【发布时间】:2017-01-17 07:31:17
【问题描述】:

我写了下面的代码来读取一个 xml 并返回一个 hashmap:

this.xmlObjectRepositoryLoader = function (xmlPath, callback){
        var map = {}
        var innerMap = {};
        var el;
        fs.readFile(xmlPath, "utf-8",function(err, data) {
            if(err){
                console.log('File not found!!')
            }
            else{
                console.log(data)
                var doc = domparser.parseFromString(data,"text/xml");
                var els = doc.getElementsByTagName("Child");
                for(var i =0 ; i< els .length;i++){
                    var e = elements[i];
                    eName = e.getAttribute("a");
                    var params = elm.getElementsByTagName("abc");
                    innerMap = {};
                    for(var j =0 ; j< params.length;j++){
                        var param = params[j];
                        var b = param.getAttribute("b");
                        var c= param.getAttribute("c");
                        innerMap[b] = c;
                    }
                    map[el] = innerMap;
                    innerMap={};
                };
            }
            console.log(map);
            return callback(map);
        });        
    };

我正在从下面的方法调用xmlObjectRepositoryLoader,但它返回错误为TypeError: callback is not a function

this.objectLoader = function(filePath){
        if (filePath.includes(".xml")) {
            console.log(this.xmlObjectRepositoryLoader(filePath));
    }

你能告诉我我错在哪里以及如何解决这个问题

【问题讨论】:

  • 希望在投反对票之前,人们也应该给出理由。无论如何感谢您的观看。

标签: javascript node.js callback typeerror


【解决方案1】:

您正在尝试拨打callback,这里:

return callback(map);

但是,您没有将回调传递给xmlObjectRepositoryLoader

console.log(this.xmlObjectRepositoryLoader(filePath));

改为这样做:

this.xmlObjectRepositoryLoader(filePath, function(map){ 
    console.log(map)
});

【讨论】:

    【解决方案2】:

    因为我没有评论的声誉。我正在回答这个问题。对此感到抱歉。你错过了下面代码中的参数

    this.objectLoader = function(filePath){
            if (filePath.includes(".xml")) {
                console.log(this.xmlObjectRepositoryLoader(filePath));
        }
    

    this.xmlObjectRepositoryLoader(filePath)

    在上面一行。

    你可以在函数xmlObjectRepositoryLoader中包含一个验证来检查回调是否是一个函数,然后调用它以避免抛出错误(如果它不是强制参数)。

    【讨论】:

      猜你喜欢
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 2018-01-22
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多