简体   繁体   English

Redis + node.js呈现对象列表

[英]Redis + node.js render a list of objects

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. 我正在尝试使用node.js和redis,我设法使用Mustache作为模板引擎来获取一些函数来渲染单个对象。

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? 我应该将所有内容保存在js数组中并计数以确保在读取所有节点后调用render函数吗?

Probably it's really trivial but I'm not sure since it's the first time I work with redis and node 可能它真的很小但我不确定,因为这是我第一次使用redis和节点

Thanks,k. 谢谢,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: 我推荐使用async模块,除其他外,它可以将数组映射到异步函数:

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. 但是请注意, hmget将返回一个包含值的数组,这些值可能是也可能不是您要在视图中呈现的值。 If an object would be more suitable, you could try hgetall . 如果一个对象更合适,你可以尝试hgetall

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM