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

问题描述 投票:0回答:1

我有一个链接到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个回答
2
投票

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

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调用promise来以更加同步的方式解析promise。然后,包装函数返回一个promise本身,当它的主体完成时它会解析。

© www.soinside.com 2019 - 2024. All rights reserved.