首页 > 解决方案 > 似乎无法返回值,只有一个承诺

问题描述

我正在尝试编写我的第一个反应原生应用程序,所以它不会做任何真正复杂的事情,只是对事物有所了解。现在它有一个按钮,当我按下它时,它会将文本字段增加 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>
    );
  }

}

标签: javascriptreactjsreact-native

解决方案


我最近问了一个类似的问题,基本上原因是myFunction一个async函数,因此它只会返回Promise

你有两个选择,要么链 a.then要么让你的 onPress 一个async方法


onPress = async () => {
    this.setState({
      count: this.state.count+1,
      output_string: await myFunction()
    })

  } 


推荐阅读