首页 > 解决方案 > 如何从 React Native 中的异步 JS 函数返回变量的值

问题描述

我正在尝试将外部 URL 加载到 React Native 应用程序中,然后从中提取<title>元素。我不想使用WebView,因为这应该在后台发生。我正在使用dom-parser库来实现它。但是,我无法返回product_namefrom的值findproduct()。运行该函数时,它确实product_name在控制台中记录了正确的值,表明代码工作正常。但是当我想获取product_name外部的价值findproduct()并在其他地方使用它时,问题就出现了。

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. 没有其他的。我需要插入productname数据库。所以,我需要确切的值。我也试图拖延,但没有任何收获。在这种情况下,延迟似乎不起作用。它只是productname先记录,然后再记录product_name

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

我做错了什么异步功能?任何帮助将不胜感激。

标签: javascriptreact-nativedomreact-native-android

解决方案


这些async函数返回 aPromise而不是实际值。因此,要获得实际值,您必须这样做。

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

如果你想做某事,你可以这样使用它......

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

推荐阅读