【问题标题】:React.js - How to call a method after another method is fully executedReact.js - 如何在另一个方法完全执行后调用一个方法
【发布时间】:2018-10-30 02:02:21
【问题描述】:

我有两个简单的功能。单击按钮后,我试图在“handleSearchClick”函数中调用两个函数。

我想在“this.props.fetchNewsApiOrg(this.newsSourceName)”完全执行后运行“this.props.getNewsDesc()”。

代码如下:

handleSearchClick = () => {
    this.props.fetchNewsApiOrg(this.newsSourceName);
    
    this.props.getNewsDesc();
  }

你能告诉我在另一个函数完全执行后调用函数的正确方法吗?

谢谢。

【问题讨论】:

  • fetchNewsApiOrg返回一个Promise,然后await它或.then就可以了
  • @CertainPerformance 所说的。另请注意,await 只能在异步函数中使用。

标签: javascript node.js reactjs redux react-redux


【解决方案1】:

您可以将该方法作为参数传递并从 fetchNewsApiOrg() 中调用该函数。

handleSearchClick = () => {
    this.props.fetchNewsApiOrg(this.newsSourceName, this.props.getNewsDesc);
 }
...
fetchNewsApiOrg(newsSourceName,getNewDesc){
...
getNewDesc();
}

在此方法中,您必须像绑定 getNewDesc 一样, this.getNewDesc = this.getNewDesc.bind(this) 在构造函数中。

或者你可以承诺。

handleSearchClick = () => {
    this.props.fetchNewsApiOrg(this.newsSourceName).then(()=>{
    this.props.getNewsDesc();
  })

这里 fetchNewsApiOrg 应该返回一个promise

【讨论】:

  • 如果您发现这是堆栈溢出社区的解决方案,请接受它作为答案,如果您觉得有用,请点赞
猜你喜欢
  • 2014-03-21
  • 2020-01-11
  • 2020-10-11
  • 2021-02-19
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 2018-06-01
  • 2013-02-27
相关资源
最近更新 更多