javascript - Getting multiple keys using node-redis -


i'm trying bunch of keys redis instance. i'm using node-redis. i'm using loop:

for( var i=1; i<=num; ++i ){     client.get(key + ':' + num, function (err, reply) {         obj[num] = reply;     }); } return obj; 

but obj undefined. feel may having problems because get called asynchronously. there way achieve this? should store values in sorted set instead?

i'm going hazard guess based on coding interface , comments client.get() asynchronous. means calls callback function passed "sometime later", not immediately. thus, can't use synchronous coding patterns collect results multiple calls client.get() because results in obj not yet available when function returns. obj not yet populated results.

if want know when multiple asychronous calls done, have code different way. and, results available inside callback functions, not @ end of function.

in all, see multiple problems code:

  1. client.get() asynchronous hasn't finished yet when function returns
  2. you should using i, not num in client.get() call each time through for loop generates different request.
  3. the value of i in loop has frozen in closure in order retain it's value use in callback function called later.
  4. if obj undefined, may because didn't initialize empty object.

here's 1 way it:

var obj = {}; var remaining = num; for( var i=1; i<=num; ++i ){     // create closure here freeze value of in callback     (function(i) {         client.get(key + ':' + i, function (err, reply) {             obj[i] = reply;             // see if asynch calls done yet             --remaining;             if (remaining === 0) {                 // asynch calls client.get() done                 // in here, can use obj object , results put on             }         });     })(i); } 

Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -