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
}
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
});
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.