I'm experimenting with node.js and redis, and I managed to get a few functions to render single objects using Mustache as a template engine.
Now I'm a situation where I need to render items from a list, looking like this
list:$(id) = [node_id_1, node_id_2, node_id_3]
node:$(id) = {"value1":1, "value2":2, "value3":3, "value4":4 }
This is the way I work with the values
//get the list of nodes
redis.lrange('list:' + req.param.list_id, 0,-1, function(err, lastNode){
//request the parameters i need from the single node
var request = ['id','type'];
redis.hmget('node:' + lastNode, request, function(err, node){
//operations on the node
});
});
Now I want to render these nodes. But I'm not sure what's the best way to do it. Shall I save everything inside a js array and count to make sure the render function get called after all the nodes being read?
Probably it's really trivial but I'm not sure since it's the first time I work with redis and node
Thanks,k.
This is indeed a little tricky in asynchronous land. I recommend the async module, which, among other things, can map an array to an asynchronous function:
Something like:
// [nodeIds] = [1, 2, 3]
async.map(nodeIds, getNode, function (err, nodes) {
// render nodes
});
function getNode (node, next) {
redis.hmget('node' + node, ['id', 'type'], next);
}
Note, though, that hmget
will return an array with values, which may or may not be what you want to render in a view. If an object would be more suitable, you could try hgetall
.