使用hexists执行for循环检查redis,但我只得到数组中最后一项的响应。我尝试了所有方法,包括异步和堆栈溢出中的一些建议,但无法得到解决方案,不知道我错过了什么。
代码低于
reply.forEach(function(replyitem,index){
parsedReply = JSON.parse(replyitem);
if(checkMsg(parsedReply.msguuid, index) == null){
result.push(parsedReply);
}
count++;
if ((count + 1) == reply.length){
// Pass the info list to the view
cd("# of info shown when page is loaded: - " + result.length);
sendAllLocations(whorequested + ":mylocation", res, result);
}
});
function checkMsg(msgidVal, index){
redisClient.hexists(blockedlistname, msgidVal, function (rediserr, exists) {
if (rediserr) {
ce("Error " + JSON.stringify(rediserr));
} else if (!exists) {
return false;
} else {
return true;
cd(" not displaying " + msgidVal);
}
});
}
答案 0 :(得分:0)
您的checkMsg()
函数正在对redis数据库进行异步调用,但之后尝试从checkMsg()
函数返回该值。它不会那样工作。无法直接从函数返回异步值。该函数在甚至检索到异步值之前返回。并且,从异步回调中返回值,只需返回到数据库基础结构,而不是回到任何代码(例如,它没有任何用处)。
您必须以异步方式使用checkMsg进行编程。它需要一个回调或承诺,它可以返回其结果,然后所有使用checkMsg的代码都必须使用该回调来检查结果。您必须异步使用该函数,就像您在代码中具有异步操作的其他位置一样。