繁体   English   中英

似乎无法返回一个值,只有一个承诺

[英]Can't seem to return a value, only a promise

我试着写我的第一个反应原生应用程序,所以它没有做任何真正复杂的事情,只是感受事物。 现在它有一个按钮,当我按下它时,文本字段增加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()
    })

  } 

在一个then回调中设置状态,该回调链接到myFunction返回的Promise

onPress = () => {
  myFunction().then(output => {
    this.setState({
      count: this.state.count+1,
      output_string: output
    });
  })
}

更新

您还可以使用async / await语法:

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

更新

OP询问countoutput_string可以独立更新。 以下是使用async / await的示例:

onPress = async () => {
  this.setState({ count: this.state.count + 1 });  // This happens immediately
  this.setState({
    output_string: await myFunction()
  });  // This happens as soon as the Promise returned by myFunction resolves
}

myFunction删除await关键字。

就目前而言,您说该函数是异步的(因此是async关键字),它(简单来说)意味着它可能不会立即解析值。

因此,返回一个promise ,(再次,简单来说)承诺在某个时间点返回一个值。

我强烈建议阅读有关async / await的内容。

编辑:或者如果您希望函数保持异步,请使用@ brian-lives-outdoors建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM