シリーズで関数を実行します
-
14-10-2019 - |
質問
まず第一に...明けましておめでとうございます!
私に説明していただけませんか、これはどのように機能しますか? 私は閲覧しました 接続's(https://github.com/senchalabs/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?
// (...)
}
);
前もって感謝します!
解決
あなたが提供する最初の関数引数は、 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
予約済みの単語です。
他のヒント
必要に応じて、ASYNCモジュールを使用してみてください。プールをシリーズで実行したり、平行したり、使用したりできるようになります。
所属していません StackOverflow