0

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
2
  • I can't understand it the link that you gave Commented Sep 22, 2016 at 13:53
  • @dm03514 is right, you need to understand javascript nature that is asynchronous Commented Sep 22, 2016 at 14:31

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.