Reputation: 187
I would like to retrieve all data from Redis (database '10') into a JSON variable. But I'm a bit confused with asynchronous call... I've tried this:
redis = require('redis');
client = redis.createClient();
client.send_command('select', [10], redis.print);
var r = {};
client.keys('*', function (err, keys) {
keys.forEach(function(c){
client.get(c, function(err, v){
r[c] = v;
});
});
});
console.log(JSON.stringify(r));
client.quit();
But my 'r' JSON variable is empty... How can I do it using callback methods, or synchronous code?
Thanks.
Upvotes: 1
Views: 3899
Reputation: 6346
I would try using async module https://github.com/caolan/async to make it async.
redis = require('redis');
client = redis.createClient();
client.send_command('select', [10], redis.print);
var r = {};
client.keys('*', function(err, keys) {
async.each(keys, function(key, callback) {
client.get(key, function(err, value) {
r[key] = value;
callback(err);
});
}, function() {
// when callback is finished
console.log(JSON.stringify(r));
client.quit();
});
});
You can also make it synchronous, using fibrous module https://github.com/goodeggs/fibrous
Synchronous code is dangerous though!
Upvotes: 1