Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value of variable from async JS function in React Native

I'm trying to load an external URL into a React Native app and then extract the <title> element from it. I don't want to use the WebView as this should happen in the background. I'm using the dom-parser library to achieve it. However, an I'm not able to return the value of product_name from findproduct(). When running the function, it does log the correct value of product_name in the console, indicating that the code is working fine. But the problem arises when I want to take the value of product_name outside findproduct() and use it elsewhere.

async function findproduct(){
  var DomParser = require('dom-parser');
  var parser = new DomParser()
  const html = (await (await fetch(product)).text()); // html as text
  var dom = parser.parseFromString(html);
  const product_name = dom.getElementsByTagName("TITLE")[0].innerHTML;
  console.log("name="+product_name); //this logs correctly
  return product_name;
}
productname = findproduct(); //this logs something else
console.log(productname);

Here, productname is either undefined or something like {"_U": 0, "_V": 0, "_W": null, "_X": null}. I searched around but all I understood was that there is some other way to return variables from an async function. Nothing else. I need to insert productname into a DB. So, I need the exact value. I also tried to give a delay but to no gain. And in this case, the delay doesn't even seem to work. It just logs productname first and then logs product_name.

setTimeout(()=>{
  productname = findproduct(product);
  console.log(productname);
},5000)

What am I doing wrong with that async function? Any help would be greatly appreciated.

like image 850
Vishal DS Avatar asked Nov 27 '25 10:11

Vishal DS


1 Answers

The async functions return a Promise instead of the actual value. So, to get the actual value, you have to do it like this.

findproduct().then((productname) => console.log(productname))

If you want to do something, you may use it like this...

findproduct().then((productname) => {
  //do what you want to do with productname
})
like image 68
Sennen Randika Avatar answered Nov 29 '25 00:11

Sennen Randika