I'm using Node.js w/ node_redis and am looping through an object and looking up data in Redis, then returning results.
I have it setup like this:
for (var key in items) {
if (items.hasOwnProperty(key)) {
app.client.llen(items[key].id+'_click', function(err, total) {
items[key].total = total;
});
}
}
callback(items);
The problem is that it loops through, before completing the call to redis. So the callback is called, before it's actually updated the total value. It also seems to skip some items due to the delay.
Is there a better way to handle this?
Thank you!
EDIT:
Ok, so I've updated it like this:
getTotal(function () {
callback(items);
});
getTotal = function (callback) {
var count = 1;
for (var key in items) {
if (items.hasOwnProperty(key)) {
app.client.llen(items[key].id + '_click', function (err, total) {
items[key].total = total;
if (items.length == count) {
callback();
}
count++;
});
};
}
This seems like it would work, it triggers the callback at the appropriate time, however it seems only the last key is getting total updated.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…