1

How is it possible that script continues even without proper setting variable? Thanks for reply!

Code

function get(param) {

  // Connect to database and get the response ~ 1 sec
  db.get(param, function(output) {

    console.log("Hey, I set the variable!");

    return output;

  });

}

try {

  var username = get("username");
  var birthday = get("birthday");

} catch (e) {

  error = e;

}

if ( !error ) {

  console.log("No errors? Everything all right?");

}

Output

No errors? Everything all right?
Hey, I set the variable!
5
  • I think there's a bunch of code you're not showing us. Commented Nov 25, 2010 at 21:56
  • Where is that first block of code? What does "few seconds later" mean ... how does that code get executed? What does that "connect to database" comment mean? What is the execution context for this code - is it in a browser or in some server-side system like Node.js? What does the code for the "get()" function really look like? Commented Nov 25, 2010 at 22:02
  • The thing is that I (and several other people) suspect what the problem is, but without seeing the real code to "get()" it's going to be very hard to say exactly what's going on. Commented Nov 25, 2010 at 22:03
  • @Pointy Okay, you are right. I added whole code. We're talking about Node.js (server-side javascript). Commented Nov 25, 2010 at 22:17
  • Where is the code for db.get? Commented Nov 25, 2010 at 22:30

2 Answers 2

1

You are thinking synchronously. What is happening is the two get statements are invoked but db has not yet invoked either callback. Your program continues merrily along checking for an error which is undefined as the catch block was never entered. As a consequence, "No errors..." is printed. Then db responds asynchronously to one of your get calls before exiting. The key thing here is you cannot assume the print statement is the result of username callback, it could be from birthday.

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

Comments

0

Though I don't know what database code that is, it's a sure bet that the function you pass in to db.get() cannot work the way your code seems to want. That function is a callback that won't be invoked until the database results are "ready" or something. You cannot have a "get()" routine that works the way yours does, in other words, because it cannot "wait" for the db.get() call.

You could rewrite your "get()" function to take its own function parameter.

Comments

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.