【问题标题】:Passing Extra Parameters in express - Node.JS在 express 中传递额外参数 - Node.JS
【发布时间】:2013-08-14 23:57:27
【问题描述】:

我正在尝试从我的节点应用程序中删除匿名函数。例如:

app.post('/page-edit.json', function (req, res) {
    db.get(req.body.page_id, function (err, doc) {
        res.contentType('json');
        res.send(doc);
    });
});

所以说我打破了内部函数:

function innerMost(err, doc) {
    res.contentType('json');
    res.send(doc);
}

function outer(err, doc) {
     db.get(req.body.page_id, innerMost);
}


app.post('/page-edit.json', outer);

问题是,我如何将额外的参数(如“res”)传递给“innerMost”?它在这个过程中迷失了。

如果你想看源代码(甚至想为开源项目做贡献!)你可以看here

【问题讨论】:

    标签: javascript node.js parameters express scope


    【解决方案1】:

    这可能是使用常规 JS 可以做到的最好的:

    function outer(req, res) {
        function innerMost(err, doc) {
            res.contentType('json');
            res.send(doc);
        }
    
        db.get(req.body.page_id, innerMost);
    }
    
    app.post('/page-edit.json', outer);
    

    但是,您可能想要查看各种异步库,例如 https://github.com/caolan/async。如果你想更进一步,你可以考虑使用 icedcoffeescript http://maxtaco.github.io/coffee-script/,我认为这非常好。

    【讨论】:

      【解决方案2】:

      听起来您正在寻找的是currying(也称为“函数的部分应用”),它基本上可以让您提前预填充一些参数的值。

      John Resig 在this 上有一篇不错的文章。

      从他的文章中获取一些代码,您可以像这样创建一个partial 函数:

      Function.prototype.partial = function(){
          var fn = this, args = Array.prototype.slice.call(arguments);
          return function(){
            var arg = 0;
            for ( var i = 0; i < args.length && arg < arguments.length; i++ )
              if ( args[i] === undefined )
                args[i] = arguments[arg++];
            return fn.apply(this, args);
          };
      };
      

      在你的情况下,像这样使用它:

      function innerMost(err, doc, req, res) {
          res.contentType('json');
          res.send(doc);
      }
      
      function outer(req, res) {
          //partially apply `innerMost` here by passing in `req` and `res`
          db.get(req.body.page_id, innerMost.partial(undefined, undefined, req, res));
      }
      
      app.post('/page-edit.json', outer);
      

      请注意,此代码未经测试。

      【讨论】:

        【解决方案3】:

        我倾向于使用 Function.bind() 将事情分开,所以你不需要弄乱 Function 的原型、外部库等。

        function innermost(req, res, e, r){
            res.end(r)
        }
        
        function somedbfunc(q, cb){
            cb(null, 'db results');
        }
        
        function outer(req, res){
            somedbfunc('query', innermost.bind(this, req, res));
        }
        
        app.all('*', outer)
            ==> "db results"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-15
          • 1970-01-01
          • 2012-06-01
          • 2017-06-01
          • 1970-01-01
          • 2020-03-12
          • 1970-01-01
          • 2017-12-18
          相关资源
          最近更新 更多