Skip to content

Instantly share code, notes, and snippets.

@ericlathrop
Last active August 29, 2015 14:10
Show Gist options
  • Save ericlathrop/05e283464c6012e4e0b9 to your computer and use it in GitHub Desktop.
Save ericlathrop/05e283464c6012e4e0b9 to your computer and use it in GitHub Desktop.
JavaScript Async Map
function asyncMap(list, iterator, callback) {
var finished = 0;
var results = [];
var firstErr;
var makeIteratorFinishCallback = function(i) {
return function(err, item) {
finished++;
if (err) {
if (!firstErr) {
firstErr = err;
callback(err);
}
return;
}
results[i] = item;
if (!firstErr && finished === list.length) {
callback(undefined, results);
}
};
};
for (var i = 0; i < list.length; i++) {
iterator(list[i], makeIteratorFinishCallback(i));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment