Search code examples
javascripttypescriptecmascript-6promisees6-promise

How to properly throw an error from the promise


I have one function, which 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)
        })
      }
    })
  }

I call it inside another component:

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

But even when updatePassword() return Error, the function call in component still console log 'successfully' from 'then`. How to properly throw an error in my case?


Solution

  • You also need to return your inner promise. Like this:

    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')
        })
      }
    

    Edit: I also added throw if you do not get user as safety net.