Permalink
Browse files

added parallel and series methods

  • Loading branch information...
1 parent 1ea1153 commit bf0dfd86bcd44ad086bb01ee15c210f2c508c596 @caolan committed May 17, 2010
Showing with 66 additions and 0 deletions.
  1. +30 −0 lib/async.js
  2. +36 −0 test/test-async.js
View
@@ -63,3 +63,33 @@ exports.waterfall = function(arr){
};
makeCallback(0)();
};
+
+exports.parallel = function(arr, callback){
+ var results = [];
+ arr.forEach(function(fn){
+ fn(function(){
+ var args = Array.prototype.slice.call(arguments);
+ results.push((args.length > 1) ? args: args[0]);
+ if(results.length == arr.length){
+ callback(results);
+ }
+ });
+ });
+};
+
+exports.series = function(arr, callback){
+ var results = [];
+ var makeCallback = function(index){
+ return function(){
+ if(index > 0){
+ var args = Array.prototype.slice.call(arguments);
+ results.push((args.length > 1) ? args: args[0]);
+ }
+ if(index < arr.length){
+ arr[index](makeCallback(index+1));
+ }
+ else callback(results);
+ }
+ };
+ makeCallback(0)();
+};
View
@@ -128,3 +128,39 @@ exports.testWaterfallMultipleCallback = function(test){
];
async.waterfall(arr);
};
+
+exports.testParallel = function(test){
+ async.parallel([
+ function(callback){
+ setTimeout(function(){callback(1);}, 100);
+ },
+ function(callback){
+ setTimeout(function(){callback(2);}, 200);
+ },
+ function(callback){
+ setTimeout(function(){callback(3,3);}, 50);
+ }
+ ],
+ function(results){
+ test.same(results, [[3,3],1,2]);
+ test.done();
+ });
+};
+
+exports.testSeries = function(test){
+ async.series([
+ function(callback){
+ setTimeout(function(){callback(1);}, 100);
+ },
+ function(callback){
+ setTimeout(function(){callback(2);}, 200);
+ },
+ function(callback){
+ setTimeout(function(){callback(3,3);}, 50);
+ }
+ ],
+ function(results){
+ test.same(results, [1,2,[3,3]]);
+ test.done();
+ });
+};

0 comments on commit bf0dfd8

Please sign in to comment.