【发布时间】:2017-03-12 17:12:17
【问题描述】:
我正在学习 nodejs、express 和 mongoose。我提出了一个关于用于从数据库中检索文档的 findOne 函数的问题。 通常,你会这样使用它:
Product.findOne({_id: req.params.id},function(error, result){
res.send(result);
});
但是当我尝试执行以下操作时,它失败了(我这样做只是为了学习):
Product.findOne({_id: req.params.id}, returnFunction(res));
function returnFunction(res,error, result){
//error and result are provided by the findOne callback function
return function(){
res.send(result); //doesnt work
};
}
但是如果我将参数传递给内部函数,它就可以完美地工作:
Product.findOne({_id: req.params.id}, returnFunction(res));
function returnFunction(res,error, result){
//error and result are provided by the findOne callback function
return function(res,result){
res.send(result);
};
}
内部函数不应该可以访问外部函数变量吗?
谢谢。
【问题讨论】:
-
是的,但是你只传递了
res所以error和result是未定义的。 -
但是函数中没有隐含的错误和结果吗?因为正如我所说,即使我没有传递那些变量,最后的代码也能完美运行。
-
它们对你返回的函数是隐含的,而不是你自己调用的那个。
-
谢谢!现在我明白了,谢谢:)
标签: javascript node.js mongodb express mongoose