尝试在异步函数中使用bcrypt散列密码 [英] Trying to hash a password using bcrypt inside an async function
问题描述
继续这个问题。
我觉得我几乎就在那里,但我对异步的不完全理解阻止了我解决这个问题。我基本上试图使用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 forbcrypt.hash
becausebcrypt.hash
does not return a promise. Use the following method, which wrapsbcrypt
in a promise in order to useawait
.
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屋!