1

I am trying to export a function which will parse a xml to json object.

export const parse = (body) => {
  const parser = new xml2js.Parser({explicitArray: false, trim: true});
  parser.parseString(body, (err, result) => {
    if (err) return err;
    parser.parseString(result['soapenv:Envelope']['soapenv:Body']['ns1:searchResponse'].searchReturn._, (err, result) => {
      if (err) return err;
      console.log(result);
      return result;
    });
  });
}

The problem I am having is that the function returns undefined, however, it manages to console.log the correct result.

2 Answers2

3

since your function is asynchronous you can convert it to promise.

export const parse = (body) => {

return new Promise((resolve, reject) => {

  const parser = new xml2js.Parser({explicitArray: false, trim: true});
  parser.parseString(body, (err, result) => {
    if (err) return reject(err);
    parser.parseString(result['soapenv:Envelope']['soapenv:Body']['ns1:searchResponse'].searchReturn._, (err, result) => {
      if (err) return reject(err);
      resolve(result);
    });
  });
  }


})

You can use it this way..

const result = await parse(<somebody>)
Muhammad Faizan
  • 1,709
  • 1
  • 15
  • 37
2

The parser is async, so you need to account for that using a callback or a promise.

const parser = new xml2js.Parser({explicitArray: false, trim: true});

export const parse = (body) => new Promise((resolve, reject) => {

  parser.parseString(body, (err, result) => {
    if(err) return reject(err);

    return resolve(result);    
  });
});

Usage.

module.parse(xml).then((parsedResult) => {

});
yBrodsky
  • 4,981
  • 3
  • 20
  • 31