【问题标题】:how to return async result from calling function如何从调用函数返回异步结果
【发布时间】:2020-03-15 18:33:08
【问题描述】:

我对异步的东西还很陌生,而且我更喜欢这个。

我正在尝试通过 mongoose 获取 mongo 查询的结果,将其与另一个值进行比较,然后从 run() 函数返回比较结果。

async run() {
        const thisHash = await this.getHashOfElement(url, '.edit-text');
        var latestHash;
        await Invitation.findOne().sort('-updated').exec(async (e, record) => { 
            if(record != undefined) {
                const latestInvitation = record;
                latestHash = latestInvitation.hash;
                console.log("latestHash inside");
                console.log(latestHash);
            } else{
                throw e;
            }
        });
        console.log('latestHash outside:');
        console.log(latestHash);
        return latestHash === thisHash;
    }

run() 函数总是返回 false,因为在进行比较时它认为 latestHash 是未定义的。

我以为它会等到 findOne() 完成,因为我把 await 放在它前面,然后执行比较。但是外部控制台日志出现在内部之前,并且是未定义的。

我需要做什么?

谢谢!

【问题讨论】:

    标签: javascript mongodb asynchronous mongoose async-await


    【解决方案1】:

    你有没有考虑过这样尝试,你需要在使用await.exec()时返回一个值

    文档:https://mongoosejs.com/docs/promises.html

    async function run() {
      try {
        const thisHash = await this.getHashOfElement(url, '.edit-text');
        const record = await Invitation.findOne().sort('-updated').exec();
    
        if (!record || !thisHash)
          throw new Error('no record');
    
        return Boolean(thisHash === record.hash);
      } catch (error) {
        throw new Error('error: ', error);
      }
    }
    

    我个人很少使用回调,因为我不希望代码看起来嵌套太多。在您的方法中,您需要将该比较移动到回调中,以便代码可以正确执行。并且还需要return await Invitation...

    【讨论】:

    • 啊太棒了,这很有效。谢谢@Duc Hong!我想我正在寻找一种没有回调的方法
    • 谢谢,请将其标记为正确答案,以供将来可能遇到与您相同问题的读者使用。
    猜你喜欢
    • 2022-12-22
    • 2023-04-01
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2016-03-11
    • 2018-01-17
    相关资源
    最近更新 更多