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:
client.get()asynchronous hasn't finished yet when function returns- you should using
i, notnuminclient.get()call each time throughforloop generates different request. - the value of
iin loop has frozen in closure in order retain it's value use in callback function called later. - if
objundefined, 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
Post a Comment