1

関数を直列に実行するとどのように機能するのか説明していただけますか?Connectのソースコード
を閲覧しましたが、わかりません。

自分で書きたいです。

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?
    // (...)
  }      
);
4

2 に答える 2

2

指定した最初の関数引数が最初に関数によって呼び出されるように見えます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したわけでもありません。msgvar

于 2011-01-01T21:12:52.237 に答える
2

必要に応じて、非同期モジュールを使用してみてください。これにより、直列、並列、またはプールの使用がはるかに簡単になります。

https://github.com/caolan/async

于 2011-12-24T00:34:34.673 に答える