尝试在异步函数中使用bcrypt散列密码 [英] Trying to hash a password using bcrypt inside an async function

查看:138
本文介绍了尝试在异步函数中使用bcrypt散列密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继续这个问题

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

I feel like I'm almost there, but my incomplete understanding of async is preventing me from solving this. I'm basically trying to just hash a password using bcrypt and have decided to seperate out the hashPassword function so that I can potentially use it in other parts of the app.

hashedPassword 保持返回未定义但是...

hashedPassword keeps returning undefined though...

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等待 bcrypt.hash 因为 bcrypt.hash 不是
返回一个承诺。使用以下方法,在承诺中包装 bcrypt ,以便使用 await

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
}

这篇关于尝试在异步函数中使用bcrypt散列密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆