Created
August 10, 2010 02:59
-
-
Save weaver/516584 to your computer and use it in GitHub Desktop.
Asynchronous map #nodejs
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
// 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