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