Dark Lord Dark Lord - 2 months ago 17
Node.js Question

Redis in Nodejs for loop not working properly

I have a for loop like below which isn't getting executed as expected.

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);
}
});
}


The output on running the below code afterwards was

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


The output:

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


which was not what i expected, since all values except the one divisible by 3 should be atleast 1;

Answer

Please create a new function. In the new function, you can delete, increment or creating the new key.

The below code works fine for me. Please check.

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);

}

Note:-

Please run the get as a separate program to check the result of the above program.

Comments