Skip to content

Instantly share code, notes, and snippets.

@gartenfeld
Created October 27, 2015 07:45
Show Gist options
  • Save gartenfeld/ecce4f087c1539fb8d78 to your computer and use it in GitHub Desktop.
Save gartenfeld/ecce4f087c1539fb8d78 to your computer and use it in GitHub Desktop.
Async mapping.
var asyncMap = function(tasks, finalCb){
var results = [];
var completed = 0;
var checkCompleteness = function() {
if (completed === tasks.length) {
finalCb(results);
}
};
var runTask = function (i) {
var onResult = function(val) {
results[i] = val;
completed++;
checkCompleteness();
};
tasks[i](onResult);
}
for(var i = 0; i < tasks.length; i++) {
// make `i` available in the closure scope
// so it can be accessed by `onResult`
runTask(i);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment