繁体   English   中英

如何通过调用 function 返回异步结果

[英]how to return async result from calling function

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

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

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() function 总是返回 false,因为在进行比较时它认为 latestHash 是未定义的。

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

我需要做什么?

谢谢!

您是否考虑过这样尝试,您需要在使用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...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM