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 Answers 2

4

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>)
Sign up to request clarification or add additional context in comments.

2 Comments

I believe you mean return resolve(result). But apart from that, it works.
Nope, you dont have to return it, resolve will return the value, i used return with reject so that function doesnt execute any further
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) => {

});

1 Comment

Or as mentioned below for usage we can use const result = await parse(<somebody>).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.