Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/39.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在mongoose virtuals中使用anync Wait?_Javascript_Node.js_Mongodb_Asynchronous_Mongoose - Fatal编程技术网

Javascript 如何在mongoose virtuals中使用anync Wait?

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;

我有这段代码,我试图用mongoose虚拟和mongoose方法将普通密码设置为加密密码 这是我的密码

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 pending

returnSecurePassword方法是异步的,它将返回一个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是的,这是承诺,您可以进一步解释我吗