在Pre Save Hook中调用异步函数正在返回我的undefined
以获取密码。我在这里从根本上误解了async
吗?我在应用程序的其他领域成功使用过它,似乎正常工作...
userSchema.pre('save', function (next) {
let user = this
const saltRounds = 10;
const password = hashPassword(user)
user.password = password;
next();
})
async hashPassword(user) {
let newHash = await bcrypt.hash(password, saltRounds, function(err, hash) {
if (err) {
console.log(err)
}
return hash
});
return newHash
}
我认为您需要处理Hashpassword返回的承诺:
hashPassword(user)
.then(password => {user.password = password
next()}
)
我认为您无法将usershema.pre变成异步函数。
mongoose钩子允许异步功能中的功能。它对我有用。请注意," Next"当函数同步执行时,异步函数中不需要回调参数。
这是问题中发布的代码的正确异步/等待版本。请注意,校正以粗体标记:
userSchema.pre('save', async function () {
let user = this;
const saltRounds = 10;
const hashed_password = await hashPassword(user.password, saltRounds);
user.password = hashed_password;
}); // pre save hook ends here
async hashPassword(password, saltRounds) {
try {
let newHash = await bcrypt.hash(password, saltRounds);
} catch(err){
// error handling here
}
return newHash;
}
只是为了清理一点:
userSchema.pre('save', function(next) {
if (!this.isModified('password')) {
return next();
}
this.hashPassword(this.password)
.then((password) => {
this.password = password;
next();
});
});
userSchema.methods = {
hashPassword(password) {
return bcrypt.hash(password, 10);
},
}
-
let user = this
在then
中使用箭头功能时可以删除。 - 当使用
bcrypt.hash()
没有回调时,它会返回承诺。 - HashPassword的异步在使用时是多余的。然后调用