Skip to content

Instantly share code, notes, and snippets.

@JosePedroDias
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosePedroDias/e1affba8a60861293076 to your computer and use it in GitHub Desktop.
Save JosePedroDias/e1affba8a60861293076 to your computer and use it in GitHub Desktop.
parallel tasks in pure JS - sample running here http://jsbin.com/weyiy/latest
// process items in parallel thingy
var parallelCbs = function(items, itemFn, cb) {
var left = items.length;
var res = new Array(left);
var cb2 = function(err, res) { // to enforce the main cb is not called more than once
if (this.called) { return; }
this.called = true;
this.cb(err, res);
}.bind({cb:cb, called:false});
cb = cb2;
var innerCb = function(err, innerRes) { // keeps track of remaining tasks
if (err) { return cb(err); }
--left;
res[this.index] = innerRes;
if (left !== 0) { return; }
cb(null, res);
};
items.forEach(function(item, index) { // invoke the function
try {
itemFn(item, innerCb.bind({index:index}));
} catch (ex) {
return cb(ex);
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment