如何从承诺中正确抛出错误

How to properly throw an error from the promise

我有一个函数,returns Promise:

  updatePassword(currentPassword: string, newPassword: string): Promise<void> {
    return this.fireAuth.currentUser.then((user: firebase.User) => {
      if (user) {
        const credentials = auth.EmailAuthProvider.credential(user.email, currentPassword)

        user.reauthenticateWithCredential(credentials).then(res => {
          if (res) {
            user.updatePassword(newPassword)
          }
        }).catch(err => {
          throw new Error(err)
        })
      }
    })
  }

我在另一个组件中调用它:

this.userService.updatePassword(currentPassword, newPassword).then(() => {
        console.log('successfully')
      }).catch(err => {
        console.log('error')
      })

但即使 updatePassword() return 错误,组件中的函数调用仍然会从 'then` 控制台记录 'successfully'。如何在我的案例中正确抛出错误?

重构您的函数以使用 async/await,您不需要手动抛出任何东西。

您可能希望将这些 return false 也变成某种 throw

  async updatePassword(currentPassword: string, newPassword: string): Promise<void> {
    const user = await this.fireAuth.currentUser;
    if(!user) return false;
    const credentials = auth.EmailAuthProvider.credential(user.email, currentPassword);
    const res = await user.reauthenticateWithCredential(credentials);
    if(!res) return false;
    user.updatePassword(newPassword);
    return true;
  }

你还需要return你内心的承诺。像这样:

updatePassword(currentPassword: string, newPassword: string): Promise<void> {
    return this.fireAuth.currentUser.then((user: firebase.User) => {
      if (user) {
        const credentials = auth.EmailAuthProvider.credential(user.email, currentPassword)

       return user.reauthenticateWithCredential(credentials).then(res => {
          if (res) {
            user.updatePassword(newPassword)
          }
        }).catch(err => {
          throw new Error(err)
        })
      }

      throw new Error('USER_NOT_FOUND')
    })
  }

编辑: 如果你没有得到 user 作为安全网,我还添加了 throw

如果您的 fireAuth 调用失败,则从 updatePassword catch 块中抛出一个 Error

检查附加的工作片段。

let fireAuth = (pass = false) => {
  if (pass) return Promise.resolve("passed");
  return Promise.reject("failed");
};

function updatePassword(shouldPass = false) {
  if (!shouldPass) {
    return fireAuth(false)
      .then(console.log)
      .catch((err) => {
      console.log('err in fireauth', err)
      throw new Error('OOPS')
    });
  }
  return Promise.resolve("success");
}

let failedResult = updatePassword()
  .then()
  .catch((err) => console.log("failedresult error", err.toString()));

let successResult = updatePassword(true)
  .then((res) => console.log("res is", res))
  .catch();