如何 return React Native 中异步 JS 函数的变量值

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

我正在尝试将外部 URL 加载到 React Native 应用程序中,然后从中提取 <title> 元素。我不想使用 WebView as this should happen in the background. I'm using the dom-parser 库来实现它。但是,我无法从 findproduct() return product_name 的值。当 运行 函数时,它确实在控制台中记录了 product_name 的正确值,表明代码工作正常。但是当我想在 findproduct() 之外获取 product_name 的值并在其他地方使用它时,问题就出现了。

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);

此处,productname 未定义或类似于 {"_U": 0, "_V": 0, "_W": null, "_X": null}。我四处搜索,但我只知道还有其他方法可以从 async function 获取 return 变量。没有其他的。我需要将 productname 插入数据库。所以,我需要确切的价值。我也试图延迟但没有收获。在这种情况下,延迟似乎甚至不起作用。它只是先记录 productname 然后记录 product_name.

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

我在那个异步函数上做错了什么?任何帮助将不胜感激。

async函数return一个Promise而不是实际值。因此,要获得实际值,您必须这样做。

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

如果你想做点什么,你可以这样使用...

findproduct().then((productname) => {
  //do what you want to do with productname
})

@Sennen Randika 是正确的,我只是添加资源以便您可以了解更多相关信息,因为异步函数和承诺对于 JavaScript 和一般来说非常重要。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

https://javascript.info/async-await#:~:text=Async%20functions&text=The%20word%20%E2%80%9Casync%E2%80%9D%20before%20a,in%20a%20resolved%20promise%20automatically.&text=So%2C%20async%20ensures%20that%20the,wraps%20non%2Dpromises%20in%20it.