Created
May 20, 2011 18:29
-
-
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
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
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