0

How does this function returns null? is it because of the variable scope or execution time of the functions?

async function getBook() {
      var book;
      await libray.findONe({ cat: 1 }, {}, async (err, res) => {
        await section.findONe({ secId: res.secI }, {}, (error, result) => {
          book = result;
        });
      });
    
      book = result;
    }


return book;
}
1
  • 1
    You will never succeed here mixing callbacks and await. await only does something useful when it's awaiting a promise and when you pass a callback to your database functions, they do not return a promise. Please take a second to learn what await really does and how to use it and how to use promises with your database. You can't just through and await in anywhere and expect it to do something useful. Commented Jan 17, 2021 at 6:49

2 Answers 2

2

Try this

async function getBook() {
      const res = await libray.findOne({ cat: 1 });
      const book = await section.findOne({ secId: res.secI });
      return book;
    }
Sign up to request clarification or add additional context in comments.

Comments

0

I think the problem is that you are returning from the function before the async function finishes. so one convenient way to solve this is to make a callback function from the async function.

Sorry I am not a js guy so I can't actually post code but I think you got the idea..

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.