简体   繁体   中英

Node.js - method is returning UNDEFINED when parsing XML

I'm parsing a hardcoded XML-structure inside a class in Node.js. 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?

Disclaimer: What you want can be achieved that but it may not work with future version of 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() :

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. As stated in the docs it may change in the future:

sync (default false): Should the callbacks be async? This might be an incompatible change if your code depends on sync execution of callbacks. Future versions of xml2js might change this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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