javascript - 似乎无法返回值,只有一个承诺
问题描述
我正在尝试编写我的第一个反应原生应用程序,所以它不会做任何真正复杂的事情,只是对事物有所了解。现在它有一个按钮,当我按下它时,它会将文本字段增加 1,我还希望该按钮现在显示来自我已导入的另一个函数的一些文本。
我有我的主 App.js 和另一个我导入到 App.js 的文件,其中包含一个返回字符串值的函数
import { myFunction } from './JSFunctions/functions.js'
myFunction 自行运行良好,并将通过 console.log 将其结果打印到控制台,但是当我添加该行时
return output
我得到的只是
Promise { <pending> }
我意识到我需要通过使用await
或.then
以某种方式转换承诺,但我已经在桌子上敲了几个小时试图让它工作但我只是得到了错误。
这是功能
export async function myFunction(){
\\lots of other code here that has been removed
var i;
var output;
for (i = 0; i < length; i++) {
output = DO STUFF AND CREATE A LONG STRING HERE
console.log(output) //produces the correct output to console
}
return output;
}
这是 App.js 中的函数
export default class App extends React.Component {
constructor(props) {
super(props)
this.state = {
count: 0,
output_string: ''
}
}
onPress = () => {
this.setState({
count: this.state.count+1,
output_string: myFunction()
})
}
render(){
const handlePress = () => false
return (
<React.Fragment>
<View style = {styles.container}>
<TouchableOpacity
onPress={this.onPress}
>
<Text>
My First Button
</Text>
</TouchableOpacity>
<Text>Hello World! This is a text area.</Text>
<Text>{ this.state.count !== 0 ? this.state.count: null}</Text>
<Text>{this.state.output_string}</Text>
</View>
</React.Fragment>
);
}
}
解决方案
我最近问了一个类似的问题,基本上原因是myFunction
一个async
函数,因此它只会返回Promise
。
你有两个选择,要么链 a.then
要么让你的 onPress 一个async
方法
onPress = async () => {
this.setState({
count: this.state.count+1,
output_string: await myFunction()
})
}
推荐阅读
- java - 当应用程序关闭或移动到其他应用程序时重新发送代码停止
- java - 如何在“onException”中设置标题以使其在骆驼路线结束之前可见?
- ios - 未调用 iOS 后台提取
- azure - 配置 Azure DevOps 电子邮件模板
- reactjs - 在 React 中拆分字符串
- spring - Spring Security:不同路径的多个 OpenID Connect 客户端?
- sql - ALTER SESSION over Ms Access Passtrough for Oracle
- angular - 如何在 IONIC 3 的 ion-list 中验证动态离子输入
- android-studio - 如何解决android studio运行时错误?
- python - 尝试在 Django 中提供媒体文件时找不到页面 404 错误