0

I've got the following code that contains a nested redis statement

   var objList =new Array(); 

    //Hardcoded key
    client.LRANGE("user4feed","0","-1",function(err,user){
        user.forEach(function (reply, i) {
                    //console.log("    " + i + ": " + reply);
            client.HGETALL('photo:'+reply,function(err,user){
                var test = user;    //Cant go array directly, will say 'user' is undefined
                objList.push(test);
            })
        });
       console.log("List length = "+user.length);
    })

console.log("objList= "+objList); //This is never reached

However, the last console log statement is never reached. It's almost as if it's in an infinite loop...

Any idea how to get out of this?

Thanks

Community
  • 1
  • 1
p0ny
  • 329
  • 1
  • 3
  • 11
  • are you using any libraries like `async` or promises? – Gntem Apr 04 '14 at 09:01
  • Just a quick observation, but you probably better use client.EVAL for this and return a JSON or flat array/list. Saves a lot of server roundtrips+waits. – Tw Bert Apr 04 '14 at 13:20
  • No, Im not using any libraries for this simple example. Although in my main app, Im using express.js. – p0ny Apr 04 '14 at 14:52
  • Is there anyway to reach that console log statement at then end? Right now it seems as if I cant mix redis code with normal code..... – p0ny Apr 04 '14 at 14:53
  • From redis docs for LRANGE: > If start is larger than the end of the list, an empty list is returned. What does `user` look like for you? – clay Apr 04 '14 at 18:01
  • @clay I can actually print out what data user contains, which is good. However, it seems as if it won't leave the LRANGE function. I've just checked with other redis "get" commands like hkeys, and the same thing happens (I can't access anything outside of the original function, like the console.log statement at the end). Do I have to end the redis statements manually or something to make it escape? – p0ny Apr 04 '14 at 18:11
  • Maybe try commenting out the `forEach` block and look for the console. Also, is your redis connection working? If you can see `user`, then the callback was called. Also, what is the value of `user`? – clay Apr 04 '14 at 18:23
  • Wow, I just realized that the console log is working, however, it's printing out before I do anything to the objList array I created. Sorry for the confusion and thanks for the help @clay. Any ideas on how to make the console.log occur after I push to the array, rather than before it? – p0ny Apr 04 '14 at 18:36

1 Answers1

1

Your final console log is outside the redis call. So it is called immediately when NodeJS calls the redis LRANGE asynchronously. Put it inside the LRANGE callback.

clay
  • 5,917
  • 2
  • 23
  • 21