继续这个问题的讨论。
我感觉我已经接近成功了,但我的异步编程理解不够深入,这阻碍了我解决问题。我想使用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
}
bcrypt
包装在一个 Promise 中以便使用await
。不错的解决方案! - developiushashPassword
成为它自己的函数。 - Modermoasync return <value>
的操作(尽管这是一件非常棒的事情)。 - developius