【问题标题】:how to use anync await in mongoose virtuals?如何在 mongoose virtuals 中使用 anync await?
【发布时间】:2021-02-03 21:30:51
【问题描述】:

我有这段代码,我试图用 mongoose virtual 和 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;
    });
  },
};

但每当我运行它时,它都会显示承诺待处理

【问题讨论】:

  • returnSecurePassword 是一个承诺吗?如果是这样,你错过了await。此外,function await(err, hash) 也不正确。您必须删除 await。
  • @Jérôme 是的,我保证你能进一步解释一下

标签: javascript node.js mongodb asynchronous mongoose


【解决方案1】:

returnSecurePassword 方法是异步的,它会返回一个 promise。 要解决此问题,请使用带有await 的 returnSecurePassword this.encry_password = await this.returnSecurePassword(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,那么就不需要 async/await this.encry_password = this.returnSecurePassword(password) 保持原样

UserSchema.methods = {
  returnSecurePassword: function (password) {
    const saltRounds = 10
    return bcrypt.hashSync(password, saltRounds)
  },
};

【讨论】:

    猜你喜欢
    • 2017-04-28
    • 2015-07-14
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 2013-09-21
    • 2018-02-28
    • 2022-11-18
    • 1970-01-01
    相关资源
    最近更新 更多