Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 315
Daniel Siguero Avatar asked Nov 28 '22 20:11

Daniel Siguero


1 Answers

Another option is to use native util module's promisify method, available from Node 8.0:

const xml2js = require('xml2js');
const util = require('util');

xml2js.parseStringPromise = util.promisify(xml2js.parseString);

// await xml2js.parseStringPromise(.. your xml ..);
like image 121
Alex K Avatar answered Nov 30 '22 08:11

Alex K