Skip to content

Instantly share code, notes, and snippets.

@weaver
Created August 10, 2010 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaver/516584 to your computer and use it in GitHub Desktop.
Save weaver/516584 to your computer and use it in GitHub Desktop.
Asynchronous map #nodejs
// amap -- asynchronous map
//
// Maps fn over list and passes the result to callback. For example,
//
// function loadEntries(folder, callback) {
// fs.readdir(folder, function(err, files) {
// if (err) throw err;
// amap(files, callback, function(name, index, next) {
// load(path.join(folder, name), next);
// });
// });
// }
function amap(list, callback, fn) {
var result = [],
index = 0,
limit = list.length;
function next(err, value) {
if (err)
callback(err);
else {
result.push(value);
if (++index < limit) {
fn(list[index], index, next);
}
else
callback(null, result);
}
}
return limit ? fn(list[0], 0, next) : callback([]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment