使用节点js从redis获取值

时间:2015-11-19 13:20:41

标签: javascript node.js

我在下面的代码中做错了什么? left_labelright_label变量似乎永远是" true",当我知道我在Redis中将它们设置为某个字符串时。我假设它是因为client.get函数成功并返回true,但是如何让它返回实际值?

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 个答案:

答案 0 :(得分:2)

get调用是异步的,必须以这种方式处理。

建议将其与bluebird的承诺库结合使用,如redis模块的NPM文档中所建议。

这样,我们就可以宣传 redis模块并以更简单的方式使用它。

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

并使用get函数的新异步版本,如下所示。

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];
});