Created
July 15, 2011 17:57
-
-
Save munro/1085174 to your computer and use it in GitHub Desktop.
Array.prototype.asyncMap
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
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