0

I am getting undefined value of recentdate variable.When I print the value using console then It print the value successfully.When I tried to hold the value inside the variable (recentdate) then It give the undefined.I want to store the value in variable so that I can use it further.

var recentdate ;
TimeHistory.find().sort([{ CreatedDated: 'DESC' }]).limit(1).exec(function (err, date) {
      console.log("RecentDate" + JSON.stringify(date[0].CreatedDated));//print the value sucessfully
      recentdate = JSON.stringify(date[0].CreatedDated);//getting undefined value
    });

1 Answers1

0

When you pass a function as a callback (like you are passing the function to .exec, the function often runs asynchronously. That means the stuff inside the passed function will likely run after the code below. For example:

console.log('This will run first');
TimeHistory.find({}).exec(function() {
    console.log('This will run third and last');
});

console.log('This will run second');

The output of this code in the console is:

-> This will run first
-> This will run second
-> This will run third and last

So - if you try to use your recentDate below your exec method, the stuff inside has not run yet, and recentDate is still undefined.

There are many solutions, but a quick and easy one is to put your code using recentDate right inside your callback:

var recentDate;
TimeHistory.find({}).exec(function(err, results) {
    recentDate = results[0].date; // or whatever
    // now continue your processing here
});
// don't add any more code down here
arbuthnott
  • 3,819
  • 2
  • 8
  • 21