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?

abdulbarik
  • 6,101
  • 5
  • 38
  • 59
Spartan Troy
  • 949
  • 2
  • 9
  • 13

1 Answers1

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.
});
Ben Fortune
  • 31,623
  • 10
  • 79
  • 80