client.get method does not work in redis for node.js
//blog function
module.exports = {
index: function () {
var data = new Object();
data.ip = base.ip();
var redis = require("redis");
var client = redis.createClient(6379,'192.168.33.10');
client.get("foo",function(err,reply,callback)
{
var x=reply.toString();
});
data.y=x;
return data;
}
};
data.y="bar" expects but
x is not defined.
where is the problem?
abdulbari
6,2625 gold badges41 silver badges65 bronze badges
asked Sep 22, 2016 at 13:45
Spartan Troy
1,0492 gold badges10 silver badges13 bronze badges
-
I can't understand it the link that you gaveSpartan Troy– Spartan Troy2016年09月22日 13:53:50 +00:00Commented Sep 22, 2016 at 13:53
-
@dm03514 is right, you need to understand javascript nature that is asynchronousArif Khan– Arif Khan2016年09月22日 14:31:57 +00:00Commented Sep 22, 2016 at 14:31
1 Answer 1
Your problem is that client.get is an asynchronous method, which you can't return from. You need some sort of asynchronous control flow, such as callbacks.
//blog function
module.exports = {
index: function (callback) {
var data = new Object();
data.ip = base.ip();
var redis = require("redis");
var client = redis.createClient(6379, '192.168.33.10');
client.get("foo",function(err,reply) {
if(err) return callback(err);
data.y = reply.toString();
callback(null, data);
});
}
};
You'd then use it like
var obj = require('./whatever');
obj.index(function(err, result) {
//result will contain your data.
});
answered Sep 22, 2016 at 14:33
Ben Fortune
32.2k10 gold badges82 silver badges82 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js