更清洁的方式在node.js中执行多个redis查询

我做了一些node.js代码来检索在Redis数据库中的数据,但我不是很高兴,我想改善它…
基本上,我在redis db中有一个“人”的logging。 从“人”我得到“人:我”(我是一个整数)的列表,并为每个“人:我”,我做了一个额外的查询来检索密钥“人:我”散列。

这是我如何做到的:

db.smembers("people", function(err1, people){ var jsonObj; var jsonArr = []; if(!err1) { var i = 0; res.writeHead(200, {'content-type': 'application/json'}); // people will provide a list like [person:1, person:2, ..., person:n] people.forEach(function(person){ // In redis I get the hash with key "person:i" db.hgetall(person, function(err2,obj){ if(!err2){ // Add person into array jsonArr.push({ "id" : person.substring(7), "lastname" : obj["lastname"], "firstname" : obj["firstname"]}); // I'm not happy with this part where I check if I reached the last item of people array.... i = i + 1; if(i == people.length){ res.write(JSON.stringify(jsonArr)); res.end(); } } else { var jsonObj = { "error" : "database error", "message" : "Cannot get hash " + person}; res.write(JSON.stringify(jsonObj)); res.end(); } }); }); } else { jsonObj = { "error" : "database error", "message" : err1.message }; res.writeHead(200, {'content-type': 'application/json'}); res.write(JSON.stringify(jsonObj)); res.end(); } }); 

什么是最干净的(至less是更清洁)的方式来做到这一点?

你要找的是一个asynchronous控制stream程系统。 一个例子是Step或streamline.js 。

另一种方法是将stream程抽象化,为Person创build一个数据模型以获取单独的人员对象,而People模型则是人员的集合,这些模型将包含一个方法,用于根据您使用的结构提取多个人员。

编辑:我find了一个完整的节点兼容控制stream/asynchronous库列表: https : //github.com/joyent/node/wiki/modules#wiki-async-flow

编辑:在审查你的代码之后,我想到了另一种相当特殊的方法,但并没有直接解决问题的控制stream本质。

通过改变你的模式,只存储人员的密钥,你可以使用redis的SORT命令来启动整个集合。 在redis中这样做:

 > SADD people 1 2 3 4 > HMSET person:1 firstname John lastname Smith > HMSET person:2 firstname Jane lastname Smith > HMSET person:3 firstname John lastname Doe > HMSET person:4 firstname Jane lastname Doe > SORT people GET # GET person:*->firstname GET person:*->lastname 1) "1" 2) "Jane" 3) "Doe" 4) "2" 5) "Jane" 6) "Smith" 7) "3" 8) "John" 9) "Doe" 10) "4" 11) "Jane" 12) "Doe" 

这在people键中具有节省内存的额外好处,并且可以通过SORT命令的limit选项进行分页/sorting。