Javascript 如何在mongoose virtuals中使用anync Wait?
我有这段代码,我试图用mongoose虚拟和mongoose方法将普通密码设置为加密密码 这是我的密码Javascript 如何在mongoose virtuals中使用anync Wait?,javascript,node.js,mongodb,asynchronous,mongoose,Javascript,Node.js,Mongodb,Asynchronous,Mongoose,我有这段代码,我试图用mongoose虚拟和mongoose方法将普通密码设置为加密密码 这是我的密码 UserSchema.virtual("password") .set(async function (password) { this.encry_password = this.returnSecurePassword(password) }) .get(function () { return this.encry_password;
UserSchema.virtual("password")
.set(async function (password) {
this.encry_password = this.returnSecurePassword(password)
})
.get(function () {
return this.encry_password;
});
UserSchema.methods = {
returnSecurePassword: async function (password) {
const saltRounds = 10
await bcrypt.hash(password, saltRounds, function await(err, hash) {
console.log(hash);
return hash;
});
},
};
但每当我运行它时,它会说promise pendingreturnSecurePassword方法是异步的,它将返回一个promise。 要解决此问题,请使用带有
wait
like的returnSecurePassword
this.encry\u password=等待。返回安全密码(password)
其次,如果您坚持使用bcrypt.hash(),那么您应该使用Promise,类似这样的
UserSchema.methods = {
returnSecurePassword: async function (password) {
const saltRounds = 10
const hash = await new Promise((resolve, reject) => {
bcrypt.hash(password, saltRounds, function(err, hash) {
if (err) reject(err);
resolve(hash);
});
return hash;
})
};
或者使用bcrypt.hashSync,则不需要异步/等待
this.encry\u password=this.returnSecurePassword(密码)
保持原样
UserSchema.methods = {
returnSecurePassword: function (password) {
const saltRounds = 10
return bcrypt.hashSync(password, saltRounds)
},
};
returnSecurePassword
是承诺吗?如果是这样,您将错过等待
。另外,函数wait(err,hash)
不正确。您必须删除wait
@Jérôme是的,这是承诺,您可以进一步解释我吗