-1

I have declared variable at global level in function, which eventually get changed within inner function and I want to return changed variable value as outer function's value but currently getting undefined.Plz provide guidance.

function checkResult(req){
    let result = true;
    Reservation.find({result_date: req.body.res_date}, function (err,doc) {
        if (err) {console.log(err);}
        else if (reservations) {
         result = false;
         console.log(result);       
        }
    })
    console.log("Final:");
    return result; // undefined error
}
harzz
  • 15
  • 1
  • 6
  • What does reservation.find do? Most importantly, is it asynchronous? – Nicholas Tower Oct 11 '17 at 22:13
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – marvel308 Oct 11 '17 at 22:13

2 Answers2

1

You should use callback.

For example:

function checkResult(req, callback){
    let result = true;
    Reservation.find({result_date: req.body.res_date}, function (err,doc) {
        if (err) {console.log(err);}
        else if (reservations) {
            result = false;       
        }

        callback(result);
    })
}

And then use the function like this:

checkResult(req, function(result){
    console.log(result); // prints the boolean
});
Kenji Mukai
  • 599
  • 4
  • 8
0

Reservation.find looks to take in a callback which is called upon completion. If Reservation.find is asynchronous, then checkResult is telling Reservation.find to begin executing, and then will immediately return result (which is undefined).

In other words, return result; is executing before result = false; because everything inside of your anonymous function function (err,doc) happens out of the flow of the function execution.

Try performing any action that needs result within your callback (the function (err,doc) block).

Edit: which is what Kenji Mukai shows below

Tor
  • 784
  • 1
  • 13
  • 25