2011-01-01 25 views
1

まずは...ハッピーニューイヤー!関数を連続して実行する

どうすればいいですか?この機能はどうですか?私は閲覧しましたの(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? 
    // (...) 
    }  
); 

ありがとうございます!

答えて

1

あなたが提供する最初の関数引数は、最初に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); 
    } 
); 

注:ここでは

は簡単な例です。また、varmsgに変更したのは、varが予約語であるためです。

+1

ありがとう、パトリック。 – Latanmos

+0

@ラタンモス:どうぞよろしくお願いいたします。 – user113716

+0

@パトリックさらに機能があればどうしますか? 'get([fn1、fn2、fn3、...]);'のように? – Latanmos

1

必要に応じて、asyncモジュールを使用してみてください。それは、シリーズで実行したり、並列したり、プールを使用したりすることをはるかに容易にします。

https://github.com/caolan/async