0

I am using mongoose api with a Node.js/Express application. I have a get request on the client side that asks for some data, but for some reason that data never makes it to the client side. What is wrong?

Snippet of backend

app.get('/up', isLoggedIn, function(req,res){
    req.user.local.level = 2;
    req.user.save(function(err){
        res.send(req.user.local.level);
    });

});

Snippet of Frontend

function try(){
    var ks=1;
    if(true){
            $.get('/up', function(data){
                ks=data;    
            });
        }
        console.log(ks);
    }

The server console displays 2, yet the browser console still displays 1, What is wrong?

Edit
I took your advice but it still wont work. What am i doing wrong?

var ks=1;
if(true){
    jQuery.ajax({
         url:    '/up' ,
         async:   false,
         success: function(data) {
                    ks = data;
                    console.log(ks);
                  }

    });
    }
idude
  • 3,956
  • 6
  • 27
  • 41
  • 1
    Your problem is on the client. Welcome to the wonderful world of **async**! You can't do that. – SLaks Oct 12 '14 at 01:30
  • Could you explain a bit more? I want to see where the error is. – idude Oct 12 '14 at 01:30
  • 1
    @idude The code simply doesn't execute in the same order as it's written. The `$.get()` executes asynchronously or "*in its own time*" separate from the `console.log(ks);`. For a more thorough explanation, see [Why is my variable unaltered after I modify it inside of a function?](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) and [How to return the response from an Ajax call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Jonathan Lonowski Oct 12 '14 at 01:36

1 Answers1

1
    console.log(ks);

That code runs as soon as you send the request, before the response arrives.

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896