javascript – 尝试在异步函数中使用bcrypt来散列密码

this question之后.

我觉得我几乎就在那里,但我对异步的不完全理解阻止了我解决这个问题.我基本上试图使用bcrypt来散列密码并决定分离hashPassword函数,以便我可以在应用程序的其他部分使用它.

hashedPassword保持返回undefined尽管…

userSchema.pre('save', async function (next) {

  let user = this
  const password = user.password;

  const hashedPassword = await hashPassword(user);
  user.password = hashedPassword

  next()

})

async function hashPassword (user) {

  const password = user.password
  const saltRounds = 10;

  const hashedPassword = await bcrypt.hash(password, saltRounds, function(err, hash) {

    if (err) {
      return err;
    }

    return hash

  });

  return hashedPassword

}

解决方法:

await dosent wait for bcrypt.hash because bcrypt.hash does not
return a promise. Use the following method, which wraps bcrypt in a promise in order to use await.

async function hashPassword (user) {

  const password = user.password
  const saltRounds = 10;

  const hashedPassword = await new Promise((resolve, reject) => {
    bcrypt.hash(password, saltRounds, function(err, hash) {
      if (err) reject(err)
      resolve(hash)
    });
  })

  return hashedPassword
}
上一篇:复习mongoose的基本使用


下一篇:MongoDB 集合关联