Philip Johan Brun
Philip Johan Brun

Reputation: 85

React Native - Function not returning correct value

I have this little code snippet:

var okidok = parseString(myXml, (err, result) => {
  console.log(result.rss.channel[0].item); //Gives the output that I want.
  return result.rss.channel[0].item;
});

console.log(okidok); //Output is rubbish.

Why okidok is not assigned value which return from parseString. All of this is happening inside an async function.

If anyone can enlighten me, I would be very greatful!

Upvotes: 0

Views: 98

Answers (1)

Dyo
Dyo

Reputation: 4464

If this is happening inside an ES7 async function you can wait parseString function to resolve doing this :

First you'll need to promisify parseString (in case it's not already thenable) :

function parseStringPromise(text){
   return new Promise((resolve,reject) => {
      parseString(text, (err, result) => {
         if(err) return reject(err);
         return resolve(data);
      });
   });
}

Then you can await for this function to get the result outside of its scope in an async function :

async function parseXml(myXml) {
   const result = await parseStringPromise(myXml);
   var okidok = result.rss.channel[0].item;
}

Note that you can add a try/catch statement to handle errors in async function.

Edit : I forgot to tell you why.

You don't have the same result because the parseString function is a Node style callback ("nodeback") asynchronous function. Asynchronous function means that you have to wait for it to resolve in order to get the result. There's some different types of asynchronous functions, the main 2 are the callback based (like your parseString) and the promises (resolvable by .then(fn) or await in async functions).

In order to use await on a function this function needs to return a promise (that's why we promisified parseString)

Here's a promise tutorial easier to understand : https://scotch.io/tutorials/javascript-promises-for-dummies

Upvotes: 2

Related Questions