Skip to content

Instantly share code, notes, and snippets.

@ekashida
Created May 20, 2011 18:29
Show Gist options
  • Save ekashida/983495 to your computer and use it in GitHub Desktop.
Save ekashida/983495 to your computer and use it in GitHub Desktop.
Execute a collection of tasks in parallel and wait for all of them to finish before executing the callback
function doAll(collection, callback) {
var left = collection.length;
collection.forEach(function(fun) {
fun(function() {
if (--left == 0) callback();
});
});
};
var result = [];
doAll([
function(callback) {
setTimeout(function() {result.push(1); callback();}, 2000)
},
function(callback) {
setTimeout(function() {result.push(2); callback();}, 3000)
},
function(callback) {
setTimeout(function() {result.push(3); callback();}, 1000)
}
], function() { return result; }
);
// returns [3, 1, 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment