【问题标题】:ReactJS/Redux/Axios Wait for server request to finishReactJS/Redux/Axios 等待服务器请求完成
【发布时间】:2017-02-16 23:58:10
【问题描述】:

我有以下代码:

  handleDeleteBlackList(id, event) {
    this.props.actions.deleteBlackListItem(id, this.props.token);
    this.props.actions.fetchBlackListItems(this.props.token);
  }

第一行从某个 Web 服务中删除一条记录,第二行获取更新的数据。有时系统在执行第二个请求之前不会等待第一个请求完成,并且我的“更新”数据根本没有更新......

我正在寻找一些解决方案来等待第一个请求完成,然后执行第二个请求。

编辑:

我已经在使用 setTimeout 函数的解决方法,但它应该有更好的方法来修复它...

【问题讨论】:

  • 这可能会有所帮助:github.com/reactjs/redux/issues/1676
  • 你的 axios 代码在哪里?如果您使用的是 axios,那么您将能够利用它使用 Promises 来处理这样的异步事件这一事实

标签: javascript reactjs async-await redux axios


【解决方案1】:

尝试使用承诺!

查看关于 Promise 的谷歌文档!

https://developers.google.com/web/fundamentals/getting-started/primers/promises

handleDeleteBlackList(id, event) {
    return new Promise(function(accept,reject) {
        perform_first_request()
        .then(function(){
          perform_second_request()
        })
    })
}

【讨论】:

  • 我认为这是解决我的问题的最佳方法!
【解决方案2】:

也许使用异步/等待。

  async handleDeleteBlackList(id, event) {
    const actionResponse = await this.props.actions.deleteBlackListItem(id, this.props.token);
    // No idea what you have set your type: to in your action so I just made this up
    if (actionResponse && actionResponse.type === 'DELETE_SUCCESS'){
        this.props.actions.fetchBlackListItems(this.props.token);
    }
  }

这将取决于你如何组织你的行动。需要查看deleteBlackListItem的代码

【讨论】:

    【解决方案3】:

    axios中有一个方法叫finally(),在调用结束后运行。像其他方法一样; then() 和 catch(),finally() 方法在收到响应后调用。但请记住,无论您的请求结果如何(成功或失败),都会调用此方法。尝试在 finally() 方法中编写第二个请求,例如

    .finally(() => {
                    your_second_request();
                });
    

    【讨论】:

      猜你喜欢
      • 2020-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      相关资源
      最近更新 更多