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

Mod*_*rmo 8 javascript bcrypt mongoose node.js

这个问题之后.

我觉得我几乎就在那里,但我对异步的不完全理解阻止了我解决这个问题.我基本上试图使用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

}
Run Code Online (Sandbox Code Playgroud)

Aka*_*han 29

await等待bcrypt.hash因为bcrypt.hash没有回应许诺.使用以下方法,它包含bcrypt一个promise以便使用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
}
Run Code Online (Sandbox Code Playgroud)

  • 可能值得明确指出,您基本上是将 `bcrypt` 包装在一个 promise 中以便使用 `await`。不错的解决方案! (4认同)

小智 11

默认情况下,bcrypt.hash(password,10)将按承诺返回。请在这里检查

示例:运行代码,

var bcrypt= require('bcrypt');

let password = "12345";


var hashPassword = async function(){
    console.log(bcrypt.hash(password,10));
    var hashPwd = await bcrypt.hash(password,10);
    console.log(hashPwd);
}

hashPassword();
Run Code Online (Sandbox Code Playgroud)

输出:

Promise { <pending> }
$2b$10$8Y5Oj329TeEh8weYpJA6EOE39AA/BXVFOEUn1YOFC.sf1chUi4H8i
Run Code Online (Sandbox Code Playgroud)

当您await在异步函数内部使用时,它将等待直到从诺言中解决。


SLI*_*med 6

使用 bcrypt.hashSync() 方法,它是开箱即用的同步。

const hashedPassword = bcrypt.hashSync(password,saltRounds);
Run Code Online (Sandbox Code Playgroud)

  • @PrivateOmega 文档说,如果您在服务器上使用 bcrypt,则首选异步:关于定时攻击的注释 为什么建议使用异步模式而不是同步模式?如果您在简单的脚本上使用 bcrypt,那么使用同步模式就完全没问题。但是,如果您在服务器上使用 bcrypt,则建议使用异步模式。这是因为 bcrypt 完成的散列是 CPU 密集型的,因此同步版本将阻止事件循环并阻止您的应用程序为任何其他入站请求或事件提供服务。异步版本使用不会阻塞主事件循环的线程池。 (2认同)