【问题标题】:Promise inside the if() function returns undefined in Javascriptif() 函数中的 Promise 在 Javascript 中返回 undefined
【发布时间】:2020-08-22 19:45:00
【问题描述】:
// 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
  }
  )
}

这是我的主要功能。我想将“checkPassword”设置为“checkPasswordService”的返回值。而且,这是我的“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
           }
       })
    }
}

我看到了 'matttched1' 的 console.log。但是,在主函数中,console.log(returnVal) 是“未定义的”。如何从 checkPasswordService 中获取 'true' 或 'false' 的值?

【问题讨论】:

  • 您将 async/await 与回调混合在一起,您应该只使用其中之一。

标签: javascript node.js


【解决方案1】:

matchPassword() 中没有return

返回bycrypt 承诺

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

【讨论】:

    【解决方案2】:

    您的代码有问题。你们都在“等待”checkPassowrdService 的承诺,并在最后使用 .then()。两者的目的相同。

    我建议你删除最后的.then() 并改用以下代码:

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

    【讨论】:

      猜你喜欢
      • 2021-09-16
      • 2020-11-28
      • 1970-01-01
      • 2022-12-07
      • 2019-12-14
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      相关资源
      最近更新 更多