admin管理员组文章数量:1295872
I'm trying to get a bunch of keys from a redis instance. I'm using node-redis. I'm using a loop:
for( var i=1; i<=num; ++i ){
client.get(key + ':' + num, function (err, reply) {
obj[num] = reply;
});
}
return obj;
But obj
is just undefined. I feel like I may be having problems because get
is obviously called asynchronously. Is there another way to achieve this? Should I just store the values in a sorted set instead?
I'm trying to get a bunch of keys from a redis instance. I'm using node-redis. I'm using a loop:
for( var i=1; i<=num; ++i ){
client.get(key + ':' + num, function (err, reply) {
obj[num] = reply;
});
}
return obj;
But obj
is just undefined. I feel like I may be having problems because get
is obviously called asynchronously. Is there another way to achieve this? Should I just store the values in a sorted set instead?
-
1
Where is
obj
declared? – Ian Commented May 20, 2013 at 4:07
1 Answer
Reset to default 10I'm going to hazard a guess based on the coding interface and your ments that client.get()
is asynchronous. That means that it calls the callback function passed to it "sometime later", not immediately. Thus, you can't use synchronous coding patterns to collect the results from multiple calls to client.get()
because the results in obj
are not yet available when your function returns. Thus obj
is not yet populated with the results.
If you want to know when multiple asychronous calls are done, then you have to code a very different way. And, the results will ONLY be available inside the callback functions, not at the end of your function.
In all, I see multiple problems with your code:
client.get()
is asynchronous so it hasn't finished yet when your function returns- You should probably be using
i
, notnum
in yourclient.get()
call so that each time through thefor
loop generates a different request. - The value of
i
in the loop has to be frozen in a closure in order to retain it's value for use in the callback function that is called later. - If
obj
was actually undefined, then that may be because you didn't initialize it to an empty object.
Here's one way to do it:
var obj = {};
var remaining = num;
for( var i=1; i<=num; ++i ){
// create a closure here to freeze the value of i in the callback
(function(i) {
client.get(key + ':' + i, function (err, reply) {
obj[i] = reply;
// see if all asynch calls are done yet
--remaining;
if (remaining === 0) {
// all asynch calls to client.get() are done now
// in here, you can use the obj object and the results put on it
}
});
})(i);
}
本文标签: javascriptGetting multiple keys using noderedisStack Overflow
版权声明:本文标题:javascript - Getting multiple keys using node-redis - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741615109a2388483.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论