Permalink
Browse files

Add a group helper that groups an arbitrary number of parallel action…

…s into a single result parameter.
  • Loading branch information...
1 parent d63ae6d commit 7e4eacea125a8d097b8b6d884d150094bc5fb50d @creationix committed Apr 27, 2010
Showing with 47 additions and 0 deletions.
  1. +34 −0 lib/step.js
  2. +13 −0 test.js
View
@@ -86,6 +86,40 @@ function Step() {
};
};
+ // Generates a callback generator for grouped results
+ next.group = function () {
+ var localCallback = next.parallel();
+ var counter = 0;
+ var result = [];
+ var error = undefined;
+ // Generates a callback for the group
+ return function () {
+ var i = counter;
+ counter++;
+ function check() {
+ counter--;
+ if (counter === 0) {
+ // When they're all done, call the callback
+ localCallback(error, result);
+ }
+ }
+ return function () {
+ // Compress the error from any result to the first argument
+ if (arguments[0]) {
+ error = arguments[0];
+ }
+ // Send the other results as arguments
+ result[i + 1] = arguments[1];
+ if (lock) {
+ process.nextTick(check);
+ return
+ }
+ check();
+ }
+
+ }
+ };
+
// Start the engine an pass nothing to the first step.
next([]);
}
View
13 test.js
@@ -2,6 +2,19 @@ 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());
+ });
+ },
+ function (err, contents) {
+ if (err) { throw err; }
+ sys.p(contents);
+ }
+);
+
Step(
function readSelf() {
fs.readFile(__filename, this);

0 comments on commit 7e4eace

Please sign in to comment.