1

Check this piece of code

            var self = this;
            var flag = true;

            UserSessionModel.setDB(req.db);
            UserSessionModel.checkIdandToken(req.headers, function(err, result) {
               if(result.length == 0){
                  console.log(flag); // prints TRUE in console
                  flag = false;
                  res.status(400).send(self.createResponse({}, {
                     success : false,
                     message : "User Id or Token is invalid"
                  }));
              }
           });

           console.log(flag); // prints TRUE in console

At the last line, it should be FALSE. Please Guide Me

Surinder
  • 415
  • 1
  • 4
  • 16
  • 2
    It's `true` because of "asynchronicity" – I'm pretty sure the second argument of your `checkIdandToken` is a callback function. You `console.log` is executed before that code is run. – MMM Dec 19 '14 at 12:49
  • Great I got your point. can you please suggest me what can I do to overcome this problem. – Surinder Dec 20 '14 at 13:58

1 Answers1

1

Like I've mentioned in my comment, it's true because of "asynchronicity" – I'm pretty sure the second argument of your checkIdandToken is a callback function. You console.log is executed before that code is run.

Essentially you variable is changed, but after you run the console.log.

This answer explains how asynchronous code works.

Community
  • 1
  • 1
MMM
  • 7,221
  • 2
  • 24
  • 42
  • Great I got your point. can you please suggest me what can I do to overcome this problem. – Surinder Dec 19 '14 at 18:14
  • If you put your `console.log` inside your callback function, it will show the correct (expected) value. Essentially all the code you want to run after the flag is set to true needs to be within the callback function, otherwise it gets executed before the flag is set. – MMM Dec 20 '14 at 22:41