javascript - 如何从 React Native 中的异步 JS 函数返回变量的值
问题描述
我正在尝试将外部 URL 加载到 React Native 应用程序中,然后从中提取<title>
元素。我不想使用WebView,因为这应该在后台发生。我正在使用dom-parser库来实现它。但是,我无法返回product_name
from的值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)
我做错了什么异步功能?任何帮助将不胜感激。
解决方案
这些async
函数返回 aPromise
而不是实际值。因此,要获得实际值,您必须这样做。
findproduct().then((productname) => console.log(productname))
如果你想做某事,你可以这样使用它......
findproduct().then((productname) => {
//do what you want to do with productname
})
推荐阅读
- c# - 写入文件跳过最后 10-20 行
- shopify - 我们可以使用店面 GQL API 按重量过滤 shopify 产品吗?
- javascript - 我如何进一步自定义我的反应路由器 dom NavLink activeStyle
- php - 在 php mysql 中从数据库中获取时更改日期格式
- c++ - compact form of many for loop in C++
- c# - 如何在 asp.net mvc 4.5 中预加载包
- vuetify.js - v1.3.x 版本 vuetify 组件 v-treeview 的 API 文档
- javascript - 需要时获得不需要的base64('image.dir')
- java - 如何在xslt中拆分和连接字符串
- php - Laravel 查找不存在的表