0

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.

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.

I thought it would wait until the findOne() is complete, since I put await in front of it, and then perform the comparison. But the outside console log appears before the inside, and it's undefined.

What do I need to do?

Thanks!

1 Answer 1

1

Have you consider trying it like this, you need to return a value while using await with .exec()

Document: 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...

Sign up to request clarification or add additional context in comments.

2 Comments

Ah wonderful, that worked. Thanks @Duc Hong! I think I was looking for a way to do it without the callback
Thanks, please mark it as correct answer for future reader who might have same problem like yours.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.