异步NodeJS请求Redis数据库

时间:2013-12-06 10:51:04

标签: node.js redis

我需要向Redis db做几个请求,我需要请求的响应来执行下一个请求。

让我们分析一下这个例子: (我正在使用node_redis来表示请求)

var message-id = undefined;

// request the next id
client.incr("message-id", function(err, id) {
    message-id = id;
});

// use the 'next id' for storing a message
client.hmset("messages", message-id, messageContent);

这种方式不起作用,因为当我调用client.hmdet()时,message-id id仍未定义。

以下是懒惰的方式,它包括将client.hmdet()放在client.incr()回调中。     var message-id = undefined;

// request the next id
client.incr("message-id", function(err, id) {
    message-id = id;

    // use the 'next id' for storing a message
    client.hmset("messages", message-id, messageContent, function(){
        //more request here
    });
});

我认为这不是一个好的方法,因为如果我有很多链接请求,我需要将每个请求放在其先前的请求回调中,这将创建一个难以维护的代码块。

我对异步执行大量请求的最佳做法感兴趣。有人可以告诉我吗?

1 个答案:

答案 0 :(得分:1)

我建议您查看async module,它会实现您可以使用的几种模式。 你的示例异步瀑布

async.waterfall([
    function(callback){
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback){
        callback(null, 'three');
    },
    function(arg1, callback){
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
   // result now equals 'done'    
});

如果你想探索回调模式以外的其他可能性,你可以使用q module来实现promises A+