简体   繁体   English

Node.js-解析XML时方法返回UNDEFINED

[英]Node.js - method is returning UNDEFINED when parsing XML

I'm parsing a hardcoded XML-structure inside a class in Node.js. 我正在解析Node.js中的类中的硬编码XML结构。 The problem is that the parsing is done asynchronously, which causes the method to return the default value (null). 问题在于解析是异步进行的,这导致该方法返回默认值(空)。

function Codeorder() {
    // Hardcodet XML-tree as string
    this.order = "  <root> \
                            <order instancename=\"flashlibraries\" opens=\"true\" />\
                                <order instancename=\"TESTTEST\" opens=\"true\" />\
                            <order instancename=\"flashlibraries\" opens=\"false\" />\
                        </root>";
    this.orderXML = null;
}

Codeorder.prototype.getOrderedCodepieces = function(instancename) {

    var parseString = require('xml2js').parseString;
    parseString(this.order, function (err, result) {
        return result; // This doesn't work
    });

    // Return "All OK"; 
}

module.exports = Codeorder;

How to I get the method to wait for the parser to complete and then return the XML content? 如何获得等待解析器完成然后返回XML内容的方法?

Disclaimer: What you want can be achieved that but it may not work with future version of xml2js. 免责声明:您可以实现所需的功能,但可能与xml2js的未来版本不兼容。

Codeorder.prototype.getOrderedCodepieces = function(instancename) {

    var parseString = require('xml2js').parseString;
    var ret = {};
    parseString(this.order, {async: false}, function(err, data) {
      ret.err = err;
      ret.data = data;
    });
    if (ret.err) {
      throw ret.err;
    }
    return ret.data;
}

Once you have this change you can will have the data you want as the return value of getOrderedCodepieces() : 进行此更改后,就可以将所需的数据作为getOrderedCodepieces()的返回值:

var c = new Codeorder();
var data = c.getOrderedCodepieces();
console.log(JSON.stringify(data, null, 2));

This relies on the async option of the parser being supported. 这取决于所支持的解析器的async选项。 As stated in the docs it may change in the future: 文档中所述,将来可能会更改:

sync (default false): Should the callbacks be async? sync(默认为false):回调应该异步吗? This might be an incompatible change if your code depends on sync execution of callbacks. 如果您的代码取决于回调的同步执行,则这可能是不兼容的更改。 Future versions of xml2js might change this 将来的xml2js版本可能会改变这一点

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM