Surinder
Surinder

Reputation: 425

How to change global var value from local scope in express Nodejs

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

Upvotes: 1

Views: 139

Answers (1)

MMM
MMM

Reputation: 7310

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.

Upvotes: 1

Related Questions