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.
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With