Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Probleme thread function exection nodejs/redis

Probleme thread function exection nodejs/redis

Problem

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

Problem courtesy of: Vsplit

Solution

It's because client.hexists is asynchronous, so when the callback executes, the for loop has already finished. The easiest way to fix this is to break out the function:

function getIfExists(tag) {
  client.hexists('tags', tag, function(err,rep) {
    if(rep===1){
      client.hget('tags',tag,function(err,rep) {
        console.log('value:'+rep);
      });
    }
  });
}

Also, javascript's for... in... syntax is not optimal for arrays.

for(var i = 0, len = tags.length; i 

Or you can use Array.prototype.forEach:

tags.forEach(getIfExists);

That said, I'm not sure why you do the hexists at all? You could just hget it, you'll get null or the value.

Solution courtesy of: Linus Gustav Larsson Thiel

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Probleme thread function exection nodejs/redis

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×