简体   繁体   中英

Promise inside the if() function returns undefined in Javascript

// Password match var
var checkPassword = null;

// Find user by email
const auth = await Auth.findOne({ userEmail }, { userLoginInfo: 0 });

// If user does not exist
if (auth === null) {
  return res
    .status(400)
    .json({ authFailedMessage: 'Email or password is incorrect' });
} else if (auth !== null) {
  // Check password when user exists
  const returnVal = await checkPasswordService.matchPassword(
    password,
    auth.password 
  ).then((returnVal) => {
    console.log(returnVal) ----> undefined
    returnVal = checkPassword
  }
  )
}

This is my main function. I want to set 'checkPassword' to the return value from 'checkPasswordService'. And, this is my 'checkPassowrdService'.

class checkPasswordService { 
    static async matchPassword(passwordInput, passwordDB) {
        console.log('passint', passwordInput)
        console.log('passDB', passwordDB)
       await bcrypt.compare(passwordInput, passwordDB).then((isMatch) => {
           if(isMatch) {
               console.log('matttched!') -------->returning 'mattched!'
               return true
           } else {
               return false
           }
       })
    }
}

I see the console.log of 'matttched1'. However, in the main function, console.log(returnVal) is 'undefined'. How can I get the value of 'true' or 'false' from checkPasswordService?

You have no return in matchPassword()

Return the bycrypt promise

return bcrypt.compare(passwordInput, passwordDB).then((isMatch) => {..

There's a problem with your code. You are both 'awaiting' for the promise checkPassowrdService as well as using a .then() at the end. Both serve the same purpose.

I suggest you remove the .then() at the end and use the following piece of code instead:

const returnVal = await checkPasswordService.matchPassword(password, auth.password)
    returnVal = checkPassword

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM