0

I know the title is a bit vague but I don't know how else to ask this and I'm having trouble wrapping my head around async javascript.

I'm writing a nodeJS app and I want to write a function that takes some xml input, converts it to JSON, cleans it up a bit, and returns it. I'm using the xml2js module to achieve this but I'm having some trouble because xml2js is asynchronous. Here's is a simplified version of my code:

function cleanUpData(xmlData) {
    xml2js(xmlData, xml2jsCallback);

    function xml2jsCallback(err, result) {
        // do a bunch of additional cleanup
        return cleanedUpJSON;
    }
}

What I want is to be able to pass the xml to the cleanUpData function and get back the nice JSON, but since xml2js() is async, I can't really do that. I would need to do everything else I want to do inside the xml2jsCallback() function and no value would ever be returned. I'm just trying to write a simple utility function though. Is the answer that I just can't use xml2js for this purpose? I'd really appreciate some insight because I'm pretty sure I must be unfamilair with some js coding pattern that will accomplish what I need.

SpasemanSpiph
  • 187
  • 1
  • 9

1 Answers1

0

Callback syntax:

function cleanUpData(xmlData, callback) {
    xml2js(xmlData, function(err, result){
        callback(result);
    });
}

cleanUpData(xmlData, function(jsondata){
    // do stuff here with jsondata
});

Promise syntax:

function cleanUpData(xmlData) {
    return new Promise(function(done){
        xml2js(xmlData, function(err, result){
            done(result);
        });
    });
}

cleanUpData(xmlData).then(function(jsondata){
    // do stuff here with jsondata
});
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116