Nodejs中的Redis for循环不能正常工作

时间:2016-09-07 08:01:20

标签: node.js redis node-redis

我有一个像下面这样的for循环,它没有按预期执行。

var redis = require('redis');
var client = redis.createClient();
var arr = [{title:"title1"},{title:"title2"},{title:"title3"},{title:"title4"}];
for(var i =0; i<arr.length; i++){
//console.log(arr[i]);
var obj1 = arr[i];
client.get(obj1.title, function(err, response){
 if(err){
  console.log(err);
 }
 if(response){
   if(i%3==0){
     client.del(obj1.title);
   }else{
     client.incr(obj1.title);
   }
 }else{
   client.set(obj1.title, 1);
 }
});
}

之后运行以下代码的输出是

for(var i=0; i<arr.length; i++){
client.get(arr[i].title, redis.print);
}

输出:

Reply: null
Reply: null
Reply: null
Reply: null
Reply: null
Reply: null
Reply: 2

这不是我所期望的,因为除3之外的所有值都应至少为1;

2 个答案:

答案 0 :(得分:1)

var redis = require('redis');
var client = redis.createClient();
var arr = [{title:"title1"},{title:"title2"},{title:"title3"},{title:"title4"}];
for(var i =0; i<arr.length; i++){
    //console.log(arr[i]); // this is cool
    var obj1 = arr[i]; 
    client.get(obj1.title, function(err, response){
        if(err){
            console.log(err);
        }
        if(response){
            if(i%3==0){
            // mistake 1:
            // due to async op,loop will already be over and i will be 3 here
            // mistake 2:
            // obj1 will be arr[3] here, not what you were expecting :D 
                client.del(obj1.title);
            }else{
                client.incr(obj1.title);
            }`enter code here`
        }else{
            // so only the last obj gets stored.
            client.set(obj1.title, 1);
        }
});
}

答案 1 :(得分:1)

请创建一个新功能。在新功能中,您可以删除,增加或创建新密钥。

以下代码对我来说很好。请检查。

var redis = require('redis');
var client = redis.createClient();
var arr = [ {
    title : "title1"
}, {
    title : "title2"
}, {
    title : "title3"
}, {
    title : "title4"
} ];


function delOrIncr(obj1, i) {
    client.get(obj1.title, function(err, response) {
        if (err) {
            console.log(err);
        }
        if (response) {
            if (i % 3 === 0) {
                console.log('Deleting >' + obj1.title);
                client.del(obj1.title);
            } else {
                console.log('Increment >' + obj1.title);
                client.incr(obj1.title);
            }
        } else {
            console.log('Creating new >' + obj1.title);
            client.set(obj1.title, 1);
        }
    });
}

for (var i = 0; i < arr.length; i++) {
    delOrIncr(arr[i], i);

}

注意: -

请将get作为单独的程序运行,以检查上述程序的结果。