javascript - 串联执行函数

标签 javascript node.js express node.js-connect

你能给我解释一下,串联执行函数是如何工作的吗?
我浏览了Connect's source code , 但我不明白。

我想自己写。

app.get(
  '/',
  function(req, res, next) {
    // Set variable        
    req.var = 'Happy new year!';
    // Go to next function
    next();
  },
  function(req, res, next) {
    // Returns 'Happy new year!' 
    console.log(req.var); // <- HOW IS THIS POSSIBLE?
    // (...)
  }      
);

最佳答案

似乎您提供的第一个函数参数首先被 get() 函数调用。

调用时,提供3个参数给调用。在调用中,req 参数必须是一个可以为其分配属性的对象。您已分配 var 属性,并为其赋予值 'Happy new year!'

您传递的下一个函数参数通过调用 next() 参数来调用,并且再次向调用提供 3 个参数。第一个参数显然是分配给 var 属性的第一次调用的同一个对象。

因为它(显然)是同一个对象,所以您分配的属性仍然存在。

这是一个简单的例子:http://jsfiddle.net/dWfRv/1/ (打开你的控制台)

// The main get() function. It has two function parameters.
function get(fn1, fn2) {
      // create an empty object that is passed as argument to both functions.
    var obj = {};
      // create a function that is passed to the first function, 
      //   which calls the second, passing it the "obj".
    var nxt = function() {
        fn2(obj); //When the first function calls this function, it fires the second.
    };
      // Call the first function, passing the "obj" and "nxt" as arguments.
    fn1(obj, nxt);
}

// Call get(), giving it two functions as parameters
get(
  function(req, next) {
      // the first function sets the req argument (which was the "obj" that was passed).
    req.msg = 'Happy new year';
      // the second function calls the next argument (which was the "nxt" function passed).
    next();
  }, 
  function(req) {
     // The second function was called by the first via "nxt",
     //   and was given the same object as the first function as the first parameter,
     //   so it still has the "msg" that you set on it.
    console.log(req.msg);
  }
);

请注意,这是一个非常简化的示例,函数中的参数较少。也不是我将 var 更改为 msg 因为 var 是保留字。

关于javascript - 串联执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4575691/

相关文章:

node.js - Dynamodb TTL 24 小时

node.js - 尝试注册新用户或登录时出错

javascript - 尝试使用 AngularJS + $http.get 访问 Instagram API

javascript - activeform 变量未更新

javascript - 赋予 A 与 B 相同的值,但不使它们相互关联

javascript - 为什么我们不能将数据作为 javascript 对象而不是 JSON 对象发送?

javascript - 多个下拉菜单重定向到 URL ( HTML )

node.js - 吉普 : how to use new filename as parameter of write function?

mysql - 在 flutter 上向我的本地主机发出 HTTP 请求不起作用

Javascript 在 Node.js 上下文中访问 ejs 变量