【问题标题】:Sequence of actions after pressing a submit button按下提交按钮后的操作顺序
【发布时间】:2018-10-02 10:15:16
【问题描述】:

我有一个链接到 resetPasswordHandler 的按钮 - 在我输入用户电子邮件并且请求成功后,会出现一个弹出警报,要求检查用户的电子邮件,然后是模式关闭和状态模式重置。

我认为这(见下面的代码)会起作用。但是当我按下提交按钮时,模式会在弹出窗口出现之前重置并关闭。

我不知道哪里出错了。

    resetPasswordHandler = () => {
    console.log("Resetting Password")
    firebase.auth().sendPasswordResetEmail(this.state.controls.email.value).then(
        alert("Please Check Your Email")
    ).then(
        this.reset()
    ).then(
        this.refs.resetPasswordModal.close()
    ).catch(function(e){
        alert(e);
    })
};

【问题讨论】:

    标签: react-native activity-indicator


    【解决方案1】:

    Promise 上调用.then(...) 时,您应该传递一个函数(例如,类似于将函数传递给按钮按下处理程序)。

    myPromise
      .then(() => this.props.dispatch(someAction()))
    

    现在,您正在调用函数而不是传递它。

    您的代码应如下所示,请记住这一点:

    firebase.auth().sendPasswordResetEmail(this.state.controls.email.value)
      .then(
        () => alert("Please Check Your Email")
      )
      .then(
        () => this.reset()
      )
      .then(
        () => this.refs.resetPasswordModal.close()
      )
      .catch(function(e){
        alert(e);
      })
    

    (我的例子中使用了箭头函数,当然你也可以使用function-syntax)

    您在 .catch 中正确执行了此操作,但在其他呼叫中似乎错过了它!

    您还可以使用async await 语法,这使您的代码更加同步:

    resetPasswordHandler = async () => {
      try {
        // Notice the "await" before calling the reset function, which returns a promise.
        await firebase
          .auth()
          .sendPasswordResetEmail(this.state.controls.email.value)
    
        alert("Please Check Your Email")
    
        this.reset()
    
        this.refs.resetPasswordModal.close()
      }
      catch(e) {
        alert(e);
      }
    };
    

    如果您的包装函数有 async 关键字,您可以通过使用 await 调用它们以更同步的方式解决承诺。然后,包装函数返回一个 Promise 本身,该 Promise 本身在其主体完成时解析。

    【讨论】:

    • 哈哈傻了我。感谢@stinodes 的详细解释:D
    • 没问题,碰巧是最好的。祝你好运!
    猜你喜欢
    • 2012-07-10
    • 2013-07-13
    • 2013-12-21
    • 2017-07-14
    • 2013-05-04
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    相关资源
    最近更新 更多