Skip to content
shimondoodkin edited this page Sep 14, 2010 · 5 revisions

group’s api is group()()(err, data)

this.group is a group generator. you call it once to make a group. so “var group_slots = this.group()”,
then group_slots is a callback generator so “var group_slot = group_slots()” call it for each callback you want to be generated.
Then callback must be called foreither error or success with the api “callback(err, data)”
call the callback group_slot when you have data like “group_slot(null, data)” and “group_slot(err)” on error

you have to reserve the slot within the array before calling your async function.
calling “this.group()” reserves a slot in the arguments of the next step.
also generating the callback reserves a slot within the array that will be passed to that argument,
and calling the callback fills in that slot.

also note for: if you create an empty group_slots it does not go to the next step. because it is an empty unfulfilled slot.

example:

var Step = require(__dirname + "/lib/step"),
    fs = require('fs'),
    sys = require('sys');

function my_function(arg_array,arg_callback)
Step(
  function () {
   if(arg_array.length==0)
   {
       arg_callback(null,{})  // don't create group_slots if the array is empty
                              // otherwise it will not go to the next step
   }
   else
    {
     var group_slots = this.group();
     arg_array.forEach(function (num) {
       var group_slot=group_slots();
       fs.readFile(__filename, group_slot); 
     });
   }

  },
  function (err, contents) {
    if (err) { throw err; }
      arg_callback(null,contents)
  }
);
}
my_function([1,2,3,4,5,6],function (contents){
 sys.puts(sys.inspect(contents))
})

a more compact way doing this but it is less obvious
in the following example all callbacks called “group” and some of them created inline-ly

it’s slightly complicated, but for the common use case, it’s really elegant since you’re normally just passing group() as the callback and never calling it directly especially if you like to rebase.

var Step = require(__dirname + "/lib/step"),
    fs = require('fs'),
    sys = require('sys');
Step(
  function () {
    var group = this.group();
    [1,2,3,4,5,6].forEach(function (num) {
      fs.readFile(__filename, group());  // note inline-ly created callback 
    });
  },
  function (err, contents) {
    if (err) { throw err; }
    sys.p(contents);
  }
);

Clone this wiki locally