Skip to content

Instantly share code, notes, and snippets.

@tim-smart
Created March 18, 2010 05:15
Show Gist options
  • Select an option

  • Save tim-smart/336073 to your computer and use it in GitHub Desktop.

Select an option

Save tim-smart/336073 to your computer and use it in GitHub Desktop.
var Parallel = exports.Parallel = function Parallel(actions) {
this.actions = {};
this._emitter = new process.EventEmitter();
if ('object' === typeof actions) {
var keys = Object.keys(actions);
for (var i = 0, key; key = keys[i++]; ) {
this.add(key, actions[key]);
}
}
return this;
};
Parallel.prototype.add = function add(name, action) {
this.actions[name] = action;
return this;
};
Parallel.prototype.bind = function bind() {
var callback = arguments[arguments.length - 1],
names = Array.prototype.slice.call(arguments, 0, -1);
for (var i = 0, name; name = names[i++]; ) {
this._emitter.addListener(name, callback);
}
return this;
};
Parallel.prototype.run = function run(callback) {
var count = 0,
action,
args,
keys = Object.keys(this.actions),
self = this;
for (var i = 0, key; key = keys[i++]; ) {
action = this.actions[key][0];
args = this.actions[key].slice(1);
args.push((function(name, action) {
return function() {
arguments = Array.prototype.slice.call(arguments);
arguments.unshift(name);
self._emitter.emit.apply(self._emitter, arguments);
callback.apply(self, arguments);
count--;
if (0 >= count) {
callback.call(self, null);
}
};
})(key, action));
count++;
action.apply(this, args);
}
if (0 >= count) {
callback(null);
}
return this;
};
var Parallel = require('./parallel'),
fs = require('fs');
var task = new Parallel({
one: [fs.stat, '/etc/passwd'],
two: [fs.stat, '/hello/world']
}).
bind('one', 'two', function(err, stat) {
// Do something with both tasks
}).
bind('one', function(err, passwdStat) {
// Do something with passwd stat
}).
run(function(name, err, stat) {
if (null === name) {
// Everything done!
} else if ('two' === name) {
// Handle hello/world
stat;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment