如何从外部函数在功能全球水平,这最终会内部函数内改变访问内部函数的性质与JavaScript
问题描述:
我宣布变量,我想返回改变变量的值作为外部函数的值,但目前越来越undefined.Plz提供指导。如何从外部函数在功能全球水平,这最终会内部函数内改变访问内部函数的性质与JavaScript
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
}
答
您应该使用回调。
例如:
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);
})
}
然后使用该函数是这样的:
checkResult(req, function(result){
console.log(result); // prints the boolean
});
+0
如果示例工作给你,你能接受的答案吗? :) –
答
Reservation.find
看起来采取在其完成时调用的回调。 如果Reservation.find
是异步的,那么checkResult
告诉Reservation.find
开始执行,然后立即返回result
(即undefined
)。
换句话说,return result;
正在执行之前result = false;
,因为你的匿名函数function (err,doc)
内发生的一切了函数执行的流程。
尝试执行您的回调(在function (err,doc)
块)内需要result
任何行动。
编辑:这是Kenji Mukai在下面显示的内容
reservation.find做什么?最重要的是,它是异步的吗? –
的可能的复制[如何返回从一个异步调用的响应?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – marvel308