我做了一些node.js代碼來檢索redis數據庫中的數據,但我並不真的很高興,我想改進它...
基本上,我在我的redis db中創建了一個「人員」。從「人」我得到一個「人:我」(我是一個整數)的列表,併爲每個「人:我」,我做了一個額外的查詢來檢索密鑰「人:我」的散列。在node.js中執行多個redis查詢的更清潔的方法
這是我要做的事:
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();
}
});
什麼是最乾淨的(至少清潔)的方式來做到這一點?
感謝您的建議。事情是我現在無法輕鬆修改架構。我在node.js中更多地尋找流量控制的最佳實踐,因爲我有幾個地方需要更清晰的代碼。非常感謝您的幫助(我會明確地看看您描述的解決方法)。 – Luc
感謝您的回答!它允許我找出最適合我的方式:)'排序消息desc limit 0 10獲得消息:* - > text'獲取最後10條消息。 –