I have a big problem for execute my program.
we use redis hkey and test if this key exist
hgetall tags
"X5"
"6"
"X2"
"7"
this is the program :
function firstChoiceChannel(){
var i=0;
var listRep
console.log(tags);
for(var k in tags){
console.log('@'+k+'|'+tags[k]);
client.hexists('tags',tags[k],function(err,rep){
console.log(tags[k]+"=>"+k+' i '+rep)
if(rep===1){
client.hget('tags',tags[k],function(err,rep){
console.log('value:'+rep);
})
console.log('ok');
}
});
}
}
this the execution program in console
[ 'X1', 'X2', 'X3', 'X5' ]
@0|X1
@1|X2
@2|X3
@3|X5
X5=>3 i 0
X5=>3 i 1
ok
X5=>3 i 0
X5=>3 i 1
ok
value:7
value:7
Why the variable tags[k] in sub-function client.hexists(…function(err,rep){})
is always equal to the last value of table ?
Thanks for your help
vincent
It’s because
client.hexistsis asynchronous, so when the callback executes, the for loop has already finished. The easiest way to fix this is to break out the function:Also, javascript’s
for... in...syntax is not optimal for arrays.Or you can use
Array.prototype.forEach:That said, I’m not sure why you do the
hexistsat all? You could justhgetit, you’ll getnullor the value.