2

What am I doing wrong in the code below? The left_label and right_label variables seem to always be "true", when I know I have them in the Redis set to some string. I'm assuming it's because the client.get function is successful and returns true, but how do I get it to return the actual value?

var http = require('http');
var redis = require('redis');
var client = redis.createClient(6379, 127.0.0.1);

var server = http.createServer(function (request, response) {

    var left_label = client.get('left', function(err, reply) {
        console.log(reply);
        return reply;
    });

    var right_label = client.get('right', function(err, reply) {
        console.log(reply);
        return reply;
    });

    response.writeHead(200, {"Content-Type": "text/html"});

    var swig  = require('swig');
    var html = swig.renderFile('/var/www/nodejs/index.html', {
        left: left_label,
        right: right_label
    });

    response.end(html);

});
server.listen(8000);
console.log("Server running at http://127.0.0.1:8000/");
1
  • redis access is asynchronous, reply has the actual value but left_label and right_label won't have it Commented Nov 19, 2015 at 13:40

1 Answer 1

5

The get call is asynchronous and must be handled that way.

A suggestion would be to combine it with a promise library such as bluebird as suggested in the NPM documentation for the redis module.

That way, we can promisify the redis module and use it in a more simple way.

var redis = require('redis');
bluebird.promisifyAll(redis.RedisClient.prototype);

and use the new async version of the get function, as below.

function getLabelValues(){
    var left_promise = client.getAsync("left").then(function(reply) {
        return reply;
    });

    var right_promise = client.getAsync("right").then(function(reply) {
        return reply;
    }); 

    return Promise.all([left_label, right_label]);
}

getLabelValues().then(function(results){
    //This is run when the promises are resolved
    //access the return data like below
    var left_label = results[0];
    var right_label = results[1];
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that pretty much did it. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.