如何使用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]
}

那么,如果不在async中添加发送到数据库的代码,我如何让它返回哈希密码呢?

bcrypt.hash不返回promise。

您可能需要将此函数调用封装到一个新的promise 中

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);
}
}

最新更新