开发者

Setting variable without callback

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!
开发者_如何学编程


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜