简体   繁体   English

node / mongo / functions / scoping的奇怪行为

[英]Weird behavior with node/mongo/functions/scoping

I have this express.js route 我有这个express.js路线

app.get("/explore/:category?", checkCategory, function(req, res){   
     var params = new Array();
     params["path"] = req.route.path;

     Category.findOne({hash:category}, function (err, doc) {
         params["category"] = doc;
     });

     console.log(params);

when you're inside the findOne, the doc value, and params["category"] values are just fine. 当你在findOne中时,doc值和params [“category”]值都很好。 Outside of that scope however, it disappears and params["category"] becomes "undefined." 然而,在该范围之外,它消失了,并且params [“category”]变得“未定义”。 Now after refreshing the page once, it returns to normal behavior, and seems to remain that way throughout the rest of the running of node. 现在刷新页面一次后,它将恢复正常行为,并且在节点的其余运行过程中似乎保持这种状态。

Why does this behavior occur? 为什么会出现这种情况?

This happens because the console.log gets called before the callback you pass to findOne. 发生这种情况是因为在传递给findOne的回调之前调用了console.log。 It works as expected if you change it like this: 如果你改变它,它按预期工作:

Category.findOne({hash:category}, function (err, doc) {
    params["category"] = doc;
    console.log(params);
});

Also, see answers to similar questions like this one . 此外,请参阅答案像类似的问题这一个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM