0

I have this callback function inside another function -

var getData = function(){
   var x ="";
   myCollection.find().toArray(function(err,records){ //myCollection is declared somewhere else
       x = "this is where I set my variable"; 

   });
   console.log(x); //x is just blank

}

How do I set variable x inside the callback function so that it still retains that value outside of the function scope?Is it possible?

user3273345
  • 127
  • 2
  • 9
  • 2
    Is `find().toArray(..)` an "asynchronous" operation by chance? If not, does the callback even execute once? Because in that code, there is only *one* `x` variable - so the assignment either doesn't happen, or doesn't happen soon enough. – user2864740 Mar 19 '14 at 21:39
  • Your code should work as is, provided of course that the callback function is invoked before the console.log, and actually sets the value of `x`. – Asad Saeeduddin Mar 19 '14 at 21:39
  • @user2864740 : You are probably right! I didn't think of that. – user3273345 Mar 19 '14 at 21:50
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) - its the same for every other asynchronous task (a database in your case?) – Bergi Mar 19 '14 at 21:56

0 Answers0