Permalink
Browse files

Merge pull request #1 from schloerke/chain

Open Chain
  • Loading branch information...
2 parents e9ef152 + 767889b commit e7611689824a7cd585d58e3d7d95e8887066d25d @alexkwolfe committed Mar 29, 2012
Showing with 23 additions and 20 deletions.
  1. +23 −20 lib/groupie.js
View
@@ -2,13 +2,13 @@
var sys = require('sys');
/**
- * Executes a group of functions concurrently, invoking a callback when all have completed
+ * Executes a group of functions concurrently, invoking a callback when all have completed
* or when an error occurs. Errors occur when an executed function throws an unhandled
* Error or when an error is passed to the callback.
*
- * Results are returned to the callback in the order that they are declared. The results
+ * Results are returned to the callback in the order that they are declared. The results
* of functions that complete after an error have occurred are discarded.
- *
+ *
* group([function(done){ done(null, 1); }, function(done){ done(null, 2); }], function(err, results){});
* or
* var g = group(function(err, results) {});
@@ -31,32 +31,32 @@ exports.group = function () {
var callGroupFunction = function(i, fxn) {
var done = function(err, result) {
if (errOccurred) return;
- if (err) {
+ if (err) {
errOccurred = true;
- return cb(err, results);
+ return cb(err, results);
}
results[i] = result;
items_left_to_execute--;
if (finalized && !items_left_to_execute) {
cb(null, results);
}
};
-
+
try {
fxn(done);
} catch (err) {
done(err, results);
}
};
-
+
if (fxns.length === 0 && !open)
cb(null, []);
-
+
for ( var i = 0; i < fxns.length; i++) {
callGroupFunction(i, fxns[i]);
}
-
+
if (open)
return {
add: function(fxn) {
@@ -85,33 +85,36 @@ exports.chain = function () {
var finalized = !open;
fxns = fxns || [];
-
+
var pos = 0;
+ var isThinking = false;
var results = [];
-
+
var hasMore = function() {
return fxns.length > pos;
};
-
+
var callNext = function() {
var done = function(err, result) {
+ isThinking = false;
if (err) return cb(err, results);
-
- pos++;
+
+ pos++;
results.push(result);
-
- if (hasMore())
+
+ if (hasMore())
callNext();
else if (finalized)
cb(null, results);
};
try {
+ isThinking = true;
fxns[pos](done);
} catch (err) {
cb(err, results);
}
};
-
+
if (fxns.length > 0)
callNext();
else if (!open)
@@ -121,11 +124,11 @@ exports.chain = function () {
return {
add: function(fxn) {
fxns.push(fxn);
- if (hasMore()) callNext();
+ if (! isThinking) callNext();
},
finalize: function() {
finalized = true;
- if (!hasMore()) cb(null, results);
+ if (! isThinking) cb(null, results);
}
}
-}
+}

0 comments on commit e761168

Please sign in to comment.