Executing functions in series


First of all... Happy new year!

Could you please explain to me, how does this work? I browsed throught Connect's (https://github.com/senchalabs/connect) source code, but I don't get it.

I would like to write it by myself.

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

Thanks in advance!

By : Latanmos


It appears as though the first function argument you provide gets called by the get() function first.

When it is called, 3 parameters are provided to the call. Inside the call, the req parameter must be an object to which you can assign properties. You've assigned the var property, and given it a value of 'Happy new year!'.

The next function argument you pass is called via a call to the next() parameter, and 3 parameters are again provided to the call. The first parameter is apparently the same object that was given to the first call where you assigned the var property.

Because it is (apparently) the same object, the property you assigned is still present.

Here's a simple example: http://jsfiddle.net/dWfRv/1/ (open your console)

// 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
  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).
  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.

Note that this is a very simplified example, with fewer parameters in the functions. Not also that I changed var to msg since var is a reserved word.

If you want, try using the async module. It makes thing much easier to be able to run in series, parallels or use a pool.


This video can help you solving your question :)
By: admin