1

I have asked this question .exec callback using returns is returning undefined, but console.log do have item in it

The answer does work, but it throws .exec away, I have been trying to re-implement it using .exec, however when I console.log something inside the .exec, it does print.

The reason I have been trying to use the .exec way is that a lot of StackOverflow questions use a lot .exec and I think ".exec" will be faster?

When I return it, it returns undefined. What is the cause and how can I solve it while keeping the .exec

let user = await User.findById(paymentBody.user_id)
.populate(User.schedule_table)
.exec((err, foundDocument) => {
  console.log(foundDocuments)
  return foundDocument;
});

console.log(user)

The code inside .exec (console.log(foundDocuments)), returns the result of query.

However, when I perform console.log(user) after the query, it shows undefined.

2
  • 1
    I think ".exec" will be faster? => no with and without both are equal, .exec() method just gives you better stack traces, nothing else. if you want to just return data I would suggest you to just use only .exec() don't add callback function. Commented Jun 6, 2021 at 7:58
  • for handling error i would suggest you to use try-catch block, see the similar question for the difference between with and without exec(), Commented Jun 6, 2021 at 8:08

1 Answer 1

0

You are mixing await and callbacks. Remove the callback and see if it works.

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

2 Comments

Removing callback does work, is there anyway that it'll work without removing callback? I removed the await but it still returns undefined
If you remove the await and leave the callback, you will need to take this into account, as in the current console.log after the query will still have user undefined as it runs before the callback.

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.