0

I often encounter problems in terms of design if it comes to this point:

var pages,
    book
;

Book.findOne( { title: "First Book" }, function(err, doc) {
  pages = doc.pages;

  console.log( pages );
} );

res.json(pages, 200);

pages is undefined, though I set it to doc.pages. If I move the res.json(pages, 200) into the callback of findOne this script works perfectly.

Am I following a wrong pattern/code design when it comes to JavaScript or is there a solution to keep the res.json() out of the callback, apart from making pages global?

1 Answer 1

6

The problem is that you're passing Book.findOne a callback to be executed when a match is found. Afterwards you're invoking res.json, and passing it pages as an argument. It's important to understand that the callback will not have been executed by this time. Are you able to move the response inside the callback function?

Book.findOne({title: 'First Book'}, function (err, doc) {
  res.json(doc.pages, 200)
})
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that's perfectly fine. I already assumed that this is the more common usage patten in Javascript to work via Callbacks since code is executed asynchroniosly and not strictly from one line to the other.
@daemonfire300 code is not executed asynchronously. Callbacks are called asynchronously.

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.