I wrote the code below, trying to collect the videos in an array then return. The code is wrong But I can\'t figure out the right way to do this.
var redis
Presumably the .hkeys method is asynchronous. That means you have to write code that knows when all async items are done so you can then (and only then) to your final res.send() with the accumulate of results.
There are many ways to keep track of when all the async operations are complete. My favorite is to promisfy all the involved functions and use Promise.all(). But, since you aren't using promises in this code yet, here's a method using a manual counter. Increment the counter whenever you start an async task. Decrement the counter whenever you finish an async task. When the counter hits zero, all async operations are done:
var redis = require('redis');
var client = redis.createClient();
app.get('/topvideos', function(req, res){
res.type('application/json');
var topvideos = [];
var cntRemaining = 0;
client.hkeys("topvideos", function(err,replies) {
console.log("Results for video:");
console.log(replies.length + " videos:");
replies.forEach(function (reply, i) {
++cntRemaining;
client.hget("topvideos",i, function (err, reply) {
console.log(i + ": " + reply );
topvideos.push(reply);
--cntRemaining;
if (cntRemaining === 0) {
res.send(JSON.stringify(topvideos));
}
});
});
}
});
You can use hgetall
client.hgetall("topvideos", function(err, videos){
var keys = Object.keys(videos);
res.send(JSON.stringify(keys.map(function(key){return videos[key];})));
});
Documentation
Also, I recommend to wrap all separate tasks with separate functions, like:
var async = require('async');
function getKeyValueMap(obj) {
return function(key, next) {
return next(null, obj[key]);
}
}
function getValues(obj, next) {
async.map(Object.keys(obj), getKeyValueMap(obj), next);
}
function getVideoList(next) {
client.hgetall("topvideos", function(err, videos){
if (err) return next(null, []);
getValues(videos, next);
});
}
function response(err, data) {
if (err) return res.send(err.message)
return res.send(JSON.stringify(data));
}
getVideoList(response);