JavaScript 变量 poof 在 findById 回调中不存在

标签 javascript node.js mongoose closures

在这段代码中,定义了 req 参数,但是当我进入回调内部时,它就不再存在了。不过,我仍然可以通过 res.req 访问它(很奇怪)。发生了什么?我认为该函数会在其环境中关闭。

function addDocument(req, res) {
    // in scope
    Request.findById(req.body._id, function(error, request){
        if (request) {
            // disappeared
        } else {
            res.send404('Couldn\'t find a request with that ID.');
        }
    });
}

最佳答案

在 javascript 中你可以做到这一点,一切都很简单

function addDocument(req, res) {
    // in scope
    Request.findById(req.body._id, function(error, request){
        if (request) {
            req.whatever; // What is Request.findById for ?
        } else {
            res.send404('Couldn\'t find a request with that ID.');
        }
    });
}

关于JavaScript 变量 poof 在 findById 回调中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30408650/

相关文章:

javascript - DOTENV 未正确读取变量

javascript - angularjs - 一次性绑定(bind)不会在 `ng-repeat` 中提供任何性能改进

javascript - 使用不带节点图标的 dynaTree

javascript - 隐藏父 div 并在 Angular Js 中显示 ui-view

javascript - 使用 casperjs 遇到 TypeError

mongoose - 如何解决Mongoose v5.11.0 model.find()错误: Operation `products.find()` buffering timed out after 10000ms"

javascript - javascript 函数和 javascript 对象之间的主要核心区别是什么?

javascript - 有没有办法使用 node.js 读取图像元数据

node.js - 应用程序未连接到 Mongoose 数据库

node.js - 当我尝试使用工作 URL 连接到同一个数据库时,Mongoose 永远不会返回它的 promise