0

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

Sean
  • 1,151
  • 3
  • 15
  • 37
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – idbehold May 24 '16 at 16:45

2 Answers2

4

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);
   }
});
narainsagar
  • 1,079
  • 2
  • 13
  • 29
  • Thanks mate! I am trying this out now. Ran into some further issues so won't mark your answer as accepted yet but will keep you posted. Cheers bud – Sean May 31 '16 at 07:56
1

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/

Anurag Awasthi
  • 6,115
  • 2
  • 18
  • 32
  • Thanks a lot. I ran into some other issues so will update you all once I have got this working :) – Sean May 31 '16 at 07:56