Skip to content

Instantly share code, notes, and snippets.

@catdad
Last active August 29, 2015 14:25
Show Gist options
  • Save catdad/3f998eb48b9baf6692d6 to your computer and use it in GitHub Desktop.
Save catdad/3f998eb48b9baf6692d6 to your computer and use it in GitHub Desktop.
function parallelSync(funcs, done) {
if (typeof workers === 'function') {
done = workers;
workers = 1;
}
var counter = funcs.length;
var idx = 0;
var queue = [].concat(funcs);
var results = [];
var errCount = 0;
var next = function() {
queue.shift()(nextGenerator(idx++));
};
var nextGenerator = function(idx) {
return function(err) {
if (err) {
errCount++;
}
results[idx] = [].slice.call(arguments);
if (--counter === 0) {
done(errCount ? true : undefined, results);
} else if (queue.length) {
next();
}
};
};
while (workers-- && queue.length) {
next();
}
}
function over(err, results) {
if (err) { console.log('there was an error'); }
var errors = results.filter(function(res){
return res[0];
}).map(function(res){
return res[0];
});
console.log('there are %d errors', errors.length);
console.log(errors);
console.log(results);
}
// list of tasks
var a = function(done) {
console.log('start', 'a');
setTimeout(function(){ done(undefined, 'a'); }, 200);
};
var b = function(done) {
console.log('start', 'b');
setTimeout(function(){ done('sadgsd'); }, 500);
};
var c = function(done) {
console.log('start', 'c');
setTimeout(function(){ done(undefined, 'c'); }, 100);
};
var d = function(done) {
console.log('start', 'd');
setTimeout(function(){ done(undefined, 'd'); }, 1100);
};
var e = function(done) {
console.log('start', 'e');
setTimeout(function(){ done('e error'); }, 100);
};
// call parallel with 3 workers
parallelSync([a,b,c,d,e], 3, over);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment