I am attempting to programmatically retrieve values from a Redis database in Node.js using a 'for' loop to iterate over GET requests. I am using the 'redis' node module. I am able to print the values of these requests to the server using console.log, however, I am not able to push each of these values to a global array for use in another node.js module. I am wondering if this is due to the 'global variables protection' aspect of Redis scripts. I'd also like to know if there is a workaround here.
redis-cli:
redis 127.0.0.1:6379> SET a "1"
OK
redis 127.0.0.1:6379> SET b "2"
OK
redis 127.0.0.1:6379> SET c "3"
OK
node.js:
var keys = ['a', 'b', 'c'];
var vals = [];
for(i=0; i<3; i++) {
client.get(keys[i], function(err, reply) {
console.log(reply);
vals.push(reply);
});
}
console.log(vals);
I would like for the vals array to output the values associated with a, b, and c...or 1, 2, and 3, respectively. Again, the intent is to use these values in another node module.
Is this an issue associated with global variables protection? Any obvious alternatives? Definitely feel like I am missing something obvious.
client.get
is an async
function. reply's
are getting pushed to vals
as expected, but not immediately. In near future they will be pushed to vals
. So, when you try to log vals
synchronously you will only get empty
array.
With async.js , you could do something like this:
var vals;
var keys = ['a', 'b', 'c'];
var async = require('async');
async.map(keys, client.get, function(err, results) {
vals = results;
console.log(vals);//will print what you wanted.
});
But, anyway, you cannot share vals
with other files by making it global. I suggest you to write asynchronous
getter function for vals
& make other files to call that function to get vals
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.