I'm building a very simple client/server app using node.js and redis for the first time. After successfully firing up my redis client and my http server, I'm trying to do a simple SET/GET with my redis client.
I first do:
client.set('apple', 10, redis.print);
which returns a Reply:Ok.
Immediately after, I execute:
client.get('apple', function(err, reply) {
count = parseInt(reply);
return count;
});
Strangely, upon printing out count, I get undefined. But, if I use redis.print, such as:
client.get('apple', redis.print);
A Reply: 10 is returned in the console. 10 also shows up if I do a console.log(count).
I thought maybe I was misusing the set functions in the module, but after referring to these both, I am unsure of what's causing my errors:
node_redis - github readme
redis.io API - GET
upon printing out count, I get undefined.
client.get('apple', function(err, reply) {
count = parseInt(reply);
return count;
});
console.log(count); // is this where you get undefined?
// count at this point is, in fact, undefined,
// because it's set in a callback which was not yet fired.
I don't program in node.js, so I'm not sure about benefits of returning count from the callback. Where would it return it to? Isn't it supposed to be something like this?
client.get('apple', function(err, reply) {
count = parseInt(reply);
// do something with the count here. Print it or whatever.
});
Or you could trap it in a closure, but then you'll need to somehow wait for callback to return and set the variable. How it can be done - I have no idea.
var count = null;
client.get('apple', function(err, reply) {
count = parseInt(reply);
});
// TODO: wait for callback
console.log(count);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With