按下提交按钮后的操作顺序

Sequence of actions after pressing a submit button

我有一个链接到 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);
    })
};

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语法)

您在 .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 调用它们以更同步的方式解决承诺。包装函数然后 returns 一个 promise 本身,当它的主体完成时解析。