Search code examples
javascriptjsonnode.jspromisees6-promise

Promisifying xml2js parse function (ES6 Promises)


I'm trying to refactor some node code that is a whole mess of callbacks. I thought that would be nice give promises a try for this purpose. I'm trying to convert some xml string to json with the xml2js node module. The original code was:

"use strict";

var xml2jsParser = require('xml2js').parseString;

var string = "<container><tag3>option3</tag3></container>";

xml2jsParser(string, function(err, result)
{
    console.log(result);
});

and this displays:

{ container: { tag1: [ 'option1' ], tag2: [ 'option2' ], tag3: [ 'option3' ] } }

Following the first answer on this question How do I convert an existing callback API to promises? I tried to wrap the xml2jsParser function using promises in the following way:

"use strict";

var xml2jsParser = require('xml2js').parseString;

function promisesParser(string)
{
    return new Promise(function(resolve, reject)
    {
        xml2jsParser(string, resolve);
    });
}

var string = "<container><tag3>option3</tag3></container>";

promisesParser(string).then(function(err, result){
    console.log(result);
});

This displays undefined through the console instead of the json object as expected. I don't understand why this happens as I was able to successfully do the same with other functions. I know something similar can be achieved with Bluebird promisify functionality but I'd like to do this on plain Javascript without any third party libraries.


Solution

  • You are going to need to wrap it up like this:

    return new Promise(function(resolve, reject)
    {
        xml2jsParser(string, function(err, result){
             if(err){
                 reject(err);
             }
             else {
                 resolve(result);
             }
        });
    });
    

    Then use it like this:

    promisesParser(string).then(function(result){
        console.log(result);
    }).catch(function(err){
        //error here
    });