Skip to content

Instantly share code, notes, and snippets.

@munro
Created July 15, 2011 17:57
Show Gist options
  • Save munro/1085174 to your computer and use it in GitHub Desktop.
Save munro/1085174 to your computer and use it in GitHub Desktop.
Array.prototype.asyncMap
Array.prototype.asyncMap = function (fn, callback) {
var that = this, i, count = 0, errors = [], map = [];
for (i = 0; i < this.length; i += 1) {
(function iter(i) {
fn(that[i], function (err, value) {
err && errors.push(err);
map[i] = value;
count += 1;
if (count === that.length) {
callback(errors.length ? errors : false, map);
}
});
}(i));
}
}
var redis = require('redis'),
client = redis.createClient(),
keys = ['hello', 'world'];
keys.asyncMap(function (value, callback) {
client.get(value, callback);
}, function (err, values) {
console.log(err || values);
client.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment