Monday 29 May 2017

Nodejs/Mongoskin - find() result is as expected inside function(err,res) but dissapears outside of it

Sorry, for the weird title, didnt know how else to phrase it because i honestly have no idea what is even happening.

I have the following code:

var x=0;
db.events.find({},{ID:1,_id:0}).sort({ID:-1}).limit(1).toArray(function(err,res){
    if(err){
        throw err;
    }else{
        if(res[0].ID===3){
            console.log('yay');
            x=res[0].ID;//x=3
        }        
    }
});
console.log(x);//x=0

As you can see, inside the function(err,res){} if I do res[0].ID i obtain the highest id, and then i compare it with res[0].ID===3 and the console does log 'yay' so it IS 3. So i assign it to x and log x and the console tells me x is indeed 3. But if i do console.log(x) outside of the query/function x goes back to being 0. Anyone knows why this happens?



via Inti Velasquez

No comments:

Post a Comment