Storing redis hget values into a variable in nodejs

Go To StackoverFlow.com

0

const redis = require('redis');
var client = redis.createClient();

client.on('error', function(err){
  console.log('Something went wrong ', err)
});


var getResponse = (key, field) =>{
 client.hget(key,field, function(err,reply){
    if(!err) return reply; 
    else {
    console.log(err);
    }
  });
};

var s = getResponse("employee","b");
console.log(s);

So when the output shows undefined. What am I doing wrong? How to store the return value to s?

2017-11-19 18:27
by Lakshya


0

You can use callbacks like:

var getResponse = (key, field, success, error) =>{
    client.hget(key,field, function(err,reply){
        if(!err) {
           success(reply);
         }
       else {
          error(err);
        }
   });
};

getResponse("employee","b",function success(reply){
    //here you get the reply
}, function error(err) {
        //error
});

If you are using Node version 6 or above you can use promise or async await. You can find more details on the following link: http://exploringjs.com/es6/ch_promises.html

2017-11-19 18:53
by Elka
I guess, my query want clear enough. In my original code, if use console,log(reply); instead of return reply it gives proper output. What I want is to store that output into a variable. How do I do that? Is there a data type mismatch - Lakshya 2017-11-19 19:02
if you want to store the reply value into a variable and after that manipulate it, you should do that in the success callback. The success callback is the place where you can be sure that you get the value. (async behavior) - Elka 2017-11-19 19:12
Thanks. It worked like a charm - Lakshya 2017-11-20 05:31
Ads