简体   繁体   English

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

[英]how to return async result from calling function

I'm pretty new to async stuff, and I'm rather stuck on this one.我对异步的东西很陌生,而且我更喜欢这个。

I'm trying to get the result of a mongo query via mongoose, compare it to another value, and return the comparison result from the run() 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;
    }

The run() function always returns false, since it thinks latestHash is undefined when the comparison is made. run() function 总是返回 false,因为在进行比较时它认为 latestHash 是未定义的。

I thought it would wait until the findOne() is complete, since I put await in front of it, and then perform the comparison.我以为它会等到 findOne() 完成,因为我把 await 放在它前面,然后执行比较。 But the outside console log appears before the inside, and it's undefined.但是外部控制台日志出现在内部之前,并且它是未定义的。

What do I need to do?我需要做什么?

Thanks!谢谢!

Have you consider trying it like this, you need to return a value while using await with .exec()您是否考虑过这样尝试,您需要在使用await.exec()时返回一个值

Document: https://mongoosejs.com/docs/promises.html文档: 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);
  }
}

I personally rarely use callback just because I don't want the code look nested too much.我个人很少使用回调,只是因为我不希望代码看起来嵌套太多。 In your approach, you need to move that comparison into the callback so the code can execute correctly.在您的方法中,您需要将该比较移动到回调中,以便代码可以正确执行。 And also need to return await Invitation...并且还需要return await Invitation...

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

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