for (i=0 ; i < pri.state.totalConversations; i++) {
redisclient.lindex("conversationsIDList",i, function(err,reply) {
convID = reply;
console.log("ConvID: " + "i: " + i + " "+ convID);
});
if(convID == pri.state.lastUpdatedConversationID)
break;
redisclient.hget("conversations", convID, function(err,reply) {
console.log("ConvID hget: "+ convID + " "+ reply);
data = JSON.parse(reply);
console.log("data: " +data);
});
above is a snippet of my code. redis-cli hget command returns the right answer which confirms that i have the hash setup correctly with the right key and field/values. However, the code snippet above returns “null” for hget, (convID has correct value which is the field for hget) – i dont understand why –
convIDisn’t going to be set until yourredisclient.lindexcallback returns. That isn’t going to happen until yourforloop has long been exited (since node’s event loop won’t even run until you’ve gotten out of your loop). You’re firing off a whole bunch of asynchronous requests toredisclientand not waiting for any of them to come back.It’s somewhat hard for me to tell exactly what you want to do, but you might want to look into flow-of-control libraries like Async.
It might be possible to define a boolean flag variable (scoped to your module or whatever function initiated your loop) that would be set by your first successful callback and would tell subsequent callbacks to ignore their results. But I’m just guessing. The main problem is that you’re trying to use synchronous flow-of-control in an asynchronous environment.