【问题标题】:await function didn't wait asynchronous anonymous functionawait 函数没有等待异步匿名函数
【发布时间】:2021-05-11 19:09:07
【问题描述】:

我尝试使用 await 使我的异步函数像同步任务一样工作,它适用于常规函数。但这不适用于我的匿名函数。

所以我的猫鼬模式中有这个功能:

userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
  bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    cb(err, isMatch);
  });
};

我尝试使用 bcrypt.compare 验证我的哈希密码,这需要我使用匿名函数来获取结果。

所以我尝试使用此功能比较密码:

async (email, password, h) => {
    const user = await User.findOne({email: email, isDeleted: false})
    if (!user) {
        const data = ResponseMessage.error(400, User Not Found')
        return h.response(data).code(400)
    }
    await user.comparePassword(password, (err, isMatch) => {
        if (isMatch) {
            console.log('TRUE')
            return h.response('TRUE')
        } else if (!isMatch) {
            console.log('FALSE')
            return h.response('FALSE')
        }
    })
    console.log('END OF FUNCTION')
    return h.response('DEFAULT')
}

附件:

Response

Console

我尝试运行服务器并比较密码,但它给了我 DEFAULT 的结果。我尝试使用控制台进行调试,然后它显示 TRUE/FALSEEND OF FUNCTION 之后显示。所以它证明我的函数运行良好,但我的 await 函数没有等待我的任务运行另一行。

对我的这个有什么帮助吗?

【问题讨论】:

标签: node.js mongoose hapijs


【解决方案1】:

尝试将其分配给 Promise,如下所示:

userSchema.methods.comparePassword = async (candidatePassword, cb) => {
await new Promise ((resolve, reject)=>{
 bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    resolve(cb(err, isMatch));
  });

})
};

【讨论】:

    【解决方案2】:

    您已经为比较函数提供了回调。 bcrypt docs

    "接受回调的异步方法,回调时返回一个Promise 如果 Promise 支持可用,则不指定。"

    Promise 支持可能是可用的,所以尽量不要返回回调,它看起来应该可以工作。 :-)

    顺便说一下,如果您遇到不支持 Promise 的后续 API,您可能需要查看 Node 的 util.promisify 函数。它将它们转换为基于 Promise 的函数。来自链接的文档:

    const util = require('util');
    const fs = require('fs');
    const stat = util.promisify(fs.stat);
    const stats = await stat('.');
    

    【讨论】:

      猜你喜欢
      • 2019-01-10
      • 2020-12-23
      • 2017-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 2023-03-13
      • 2019-08-28
      相关资源
      最近更新 更多