繁体   English   中英

如何使用 bcrypt 返回散列密码?

[英]How to return hashed password with bcrypt?

我正在使用 bcrypt 并且我正在尝试使用一个异步函数来散列密码并返回它,但是由于它是异步的,除非我使用同步版本(即使它有效,我也不想要)它返回[object Promise]和数据库将此: {}保存为密码。 是的两个括号。 我确实使用了await但它不起作用,而且我对异步函数的理解很差。 我在网上找不到任何答案,因为看起来我按照教程做的很好,但我显然不是。

代码如下所示:

function signup(){
     var pass = "example";
     pass = hashPassword(pass);
     
     console.log(pass); // prints [object Promise] - It's printed first.

     //write account with pass to database. Pass is saved as '{}'.
}

async function hashPassword(original_password){
     const hashedPass = await bcrypt.hash(original_password, 10);
     console.log(hashedPass) // prints the actual hashed pass - It's printed second

     return hashedPass; //returns [object Promise]
}

那么如何让它返回散列密码而不在异步中添加发送到数据库的代码呢?

bcrypt.hash 不返回承诺。

您可能需要将此函数调用包装到一个新的承诺中

const hashedPass = await new Promise((resolve, reject) => {
    bcrypt.hash(original_password, rounds, function(err, hash) {
      if (err) reject(err)
      resolve(hash)
    });

当您调用async函数时,它将返回一个promise ,请查看SO 上的这个答案

为了获得您的散列数据,您可以使用.then来解决您的承诺

hashPassword(pass).then(hash=>console.log(hash)).catch(err=>console.error(err))

或者你也可以使用async/await

async function signup() {
  try {
    var pass = "example";
    pass = await hashPassword(pass);
  } catch (err) {
    console.error(err);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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