0

I am sure there is a simple answer to this. I just can't seem to get my head fully around Promises.

From everything I have reading, the below code should be behaving as I expect.

From what I can gather, Post.findById should await, then the following console.log('A') should execute before console.log('B'). However that is not happening. console.log('B') is executing before console.log('A').

It appears the await in let parent_post = await Post.findById is having no effect, and console.log('B') is running before console.log('B').

Any suggestions on what I may be doing wrong with this?

exports.save = async function(req, res) {

        let parent_post = await Post.findById(req.body.comment_of)
          .populate("starred_users", "name email")
          .exec(function(err,parent_post){
              console.log('A');
              console.log(parent_post);
              return parent_post;
          });

        console.log('B');
        console.log(parent_post);

       // I need to do stuff to parent_post here before returning

        return parent_post

}

Thanks in advance.

Jason
  • 1,957
  • 2
  • 20
  • 34
  • Seems that you should *either* pass a callback *or* `await` the result. Not both. – VLAZ Jun 01 '22 at 12:52
  • Does this answer your question? [Mongoose - What does the exec function do?](https://stackoverflow.com/questions/31549857/mongoose-what-does-the-exec-function-do) | [Await vs exec in mongoose](https://stackoverflow.com/q/59633665) – VLAZ Jun 01 '22 at 12:56
  • Thanks gents. Both your answers helped. Seems exec() is not going to work with async/await. Need either callback or .then(). Problem is I can't find how to use .populate() with anything other than exec(). Cheers – Jason Jun 01 '22 at 13:18
  • Just don't pass a callback to `.exec()` – VLAZ Jun 01 '22 at 13:20
  • VLAZ, do you mean remove "function(err,parent_post){" from within the exec? So just use exec(console.log etc..)? If so, how do I pass parent_host into .exec() – Jason Jun 01 '22 at 13:26
  • You don't, *only* keep `.exec()` with nothing else inside the brackets. Without a callback it will return a promise-compatible object. If you `await` it, you get the result. The code `.exec(function(err,parent_post){ return parent_post; });` basically intends exactly the same anyway - you want to get `parent_post` out if it. That should be the same result as result of `await /*...*/.exec()` with no callback. – VLAZ Jun 01 '22 at 13:31
  • OK VLAZ.. That did it. So I needed to keep exec() empty, and just work on parent_post after it.. of course. Thank you. Can you post that as an answer and I can flag it as such. Cheers. – Jason Jun 01 '22 at 13:34
  • Post.findById(req.body.comment_of) .populate("starred_users", "name email") .exec(); // now work on parent_post. No need to do it inside exec(). – Jason Jun 01 '22 at 13:35

0 Answers0