Sean
Sean

Reputation: 1364

How to access a variable outside a function

Please bear with me on this. I can't seem to get my head round how I will be able to update the variable outside the FindOne function.

So:

var userPostCount;

    userPostsModel.findOne({'profileID':req.session.id}, function(err, usersPostCountDB) {
        if(usersPostCountDB){
            userPostCount = req.body.postsCount + 1;
        } else {
            console.log('There was an error getting the postsCount');
       }
    });

I thought it should be able to find the userPostCount variable as it's the next level up in the scope chain.

Any ideas how I will be able to access it please? I need that variable to be outside of the function as I will be using it later for other mongoose activities.

I am getting the userPostCount as undefined.

Thanks in advance for the help!

PS: I looked around for other questions on SO but the solution on other answers don't seem to work for me.

Shayan

Upvotes: 0

Views: 2161

Answers (2)

Anurag Awasthi
Anurag Awasthi

Reputation: 6233

You are trying to return a value from a callback function. It's easier if you try to use the result inside the callback function.

Another thing you can do is you can define a function and give it a callback where you can use the value.

function foo(fn){
     userPostsModel.findOne({'profileID':req.session.id}, function(err, usersPostCountDB) {
    if(usersPostCountDB){
        userPostCount = req.body.postsCount + 1;
        fn(userPostCount);
    } else {
        console.log('There was an error getting the postsCount');
   }
});
}
foo(function(userPostCount){
    alert(userPostCount);
})

If you're using jquery, you can use deferred objects. http://api.jquery.com/category/deferred-object/

Upvotes: 1

narainsagar
narainsagar

Reputation: 1129

please use callbacks.

function getPostsCount(callback) {
    userPostsModel.findOne({'profileID':req.session.id}, function(err, usersPostCountDB) {
        if(usersPostCountDB) {
            callback(null, req.body.postsCount + 1);
        } else {
            console.log('There was an error getting the postsCount');
            callback(true, null);
       }
    });
}

and from outside call it by passing callback function as an argument. so the callback function will be executed right after getPostsCount() returns (finishes)..

getPostsCount(function(error, postsCount) {
   if (!error) {
      console.log('posts count: ', postsCount);
   }
});

Upvotes: 4

Related Questions