我在执行我的程序时遇到了一个大问题。 我们使用 redis hkey 并测试这个键是否存在
hgetall tags
"X5"
"6"
"X2"
"7"
这是程序:
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');
}
});
}
}
这是控制台中的执行程序
[ '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
为什么子函数 client.hexists(...function(err,rep){}) 中的变量 tags[k] 总是等于表的最后一个值?
谢谢你的帮助
文森特
最佳答案
因为client.hexists
是异步的,所以回调执行的时候,for循环已经结束了。解决此问题的最简单方法是分解函数:
function getIfExists(tag) {
client.hexists('tags', tag, function(err,rep) {
if(rep===1){
client.hget('tags',tag,function(err,rep) {
console.log('value:'+rep);
});
}
});
}
此外,javascript 的 for...in...
语法对于数组来说不是最佳的。
for(var i = 0, len = tags.length; i < len; i++) {
getIfExists(tags[i]);
}
或者你可以使用Array.prototype.forEach
:
tags.forEach(getIfExists);
就是说,我完全不确定您为什么要执行 hexists
?你可以hget
它,你会得到null
或值。
关于javascript - Probleme线程函数执行nodejs/redis,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9698178/