xml2js: access xml node attribute with promises

In one of the previous examples we considered reading attribute value of using xml2jsparseString operation is asynchronous which means that if you may need to wait for completion of the operation, you have to handle it by yourself. One of the ways to wait for operation completion is using Promises. My favorite definition of promises is "a promise represents the eventual result of an asynchronous operation. It is a placeholder into which the successful result value or reason for failure will materialize". So, let's get back now to our practical example. We will use the same xml and we will solve the same task (reading attribute value of using xml2js). Except one thing: we need a new function where a promise will be created.

function getXmlAttribute () {
  return new Promise(function (resolve, reject) {
    parser.parseString(xml, function(err, result) {
      extractedData = result['apps']['app'][1].$.type;
      if (err) return reject(err)    // rejects the promise with `err` as the reason
      resolve(extractedData)        // fulfills the promise with `extractedData` as the value
    })
  })
}

It's not done yet. How can we utilize promises now? Simply using then() method, and we will deal with data returned with getXmlAttribute() exactly inside then():

getXmlAttribute().then( value => {
    // code which has to deal with extracted value goes here
    console.log(value);
  },
  reason => {
    console.log(reason); // Error!
} );

We are done now. Upon execution, value of parsed attribute will be printed to console. Otherwise, in case of error, reason of promise rejection will be printed out.       

Comments