【问题标题】:Removing chaining promises删除链式承诺
【发布时间】:2019-08-02 07:20:50
【问题描述】:

react-native 新手,目前我正在开发链式 Promise。

myFunction(human, destination = null) {
    const { navigation } = this.props;
    const { onRefresh } = navigation.state.params;
    this.setState({ isLoading: true });
    return PeopleService.closeService(
      human.humanId,
      destinationPoint && destinationPoint.humanId,
    )
      .then((result) => {
        if (result) {
          PeopleHelperService.refreshInfo().then(() => {
            if (onRefresh) {
              onRefresh();
            }
            navigation.popToTop();
            PopUp.showSuccess(
              "Success message",
            );
          });
        }
        PopUp.showError(
          "Failing message",
        );
        return null;
      })
      .finally(() => this.setState({ isLoading: false }));
  }

我想要实现的目标是消除链式责任并使其变得简单而无需链式。

谁能指导我如何实现这一目标?一些文档和其他来源的链接对我了解如何制作非常有帮助。

更新: 似乎是 async/await 工作的答案。

【问题讨论】:

  • 您的代码逻辑可能存在问题。如果PeopleService.closeService() 承诺解决了一个真实的result,那么将显示两个弹出窗口。我猜。

标签: javascript reactjs react-native chaining method-chaining


【解决方案1】:

如果您不想使用 Promise,请使用异步等待。在这里。

myFunction = async (human, destination = null) => {
    const { navigation } = this.props;
    const { onRefresh } = navigation.state.params;
    this.setState({ isLoading: true });
    let result = await PeopleService.closeService(
      human.humanId,
      destinationPoint && destinationPoint.humanId,
    );

    if (result) {
        await PeopleHelperService.refreshInfo();
        if (onRefresh) {
            onRefresh();
        }
        navigation.popToTop();
        PopUp.showSuccess(
            "Success message",
        );
    }
    PopUp.showError(
        "Failing message",
    );
    this.setState({ isLoading: false })
}

【讨论】:

  • 需要为 finally 块添加try-catch
  • 我已经在尝试异步/等待,希望它会有所帮助,但它只会在我按下 closeService 按钮时创建无限加载。
  • @AZ_ try-catch ?它有什么帮助?只是问,因为我有兴趣了解事物:)
  • @somerk 即使抛出错误,也必须执行 promise 的 finally 块中的代码,如果 async-await 中不包含 try-catch 块,则不会发生这种情况。
  • @AZ_ 现在无限加载消失了,但我的弹出窗口似乎不想出现
猜你喜欢
  • 2017-03-13
  • 1970-01-01
  • 1970-01-01
  • 2018-09-04
  • 2014-08-12
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 2021-02-27
相关资源
最近更新 更多