Last active
August 29, 2015 14:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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