【问题标题】:Async NodeJS request to Redis db对 Redis 数据库的异步 NodeJS 请求
【发布时间】:2013-12-06 21:30:55
【问题描述】:

我需要对 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
    });
});

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

我对异步处理大量请求的最佳做法感兴趣。有人可以给我建议吗?

【问题讨论】:

  • 你在第一个代码块的第 6 行缺少一个结束符 )

标签: node.js redis


【解决方案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'    
});

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

【讨论】:

  • 谢谢! Q模块真的很有趣!
  • 无论如何,我认为如果任何 redis 方法具有将请求设置为同步或异步的标志... ;)
  • 我真的不明白如何用 Promise A+ 的方式做到这一点......我认为我没有很好地解释...... -_-'
猜你喜欢
  • 1970-01-01
  • 2020-07-21
  • 2016-09-27
  • 2013-10-23
  • 1970-01-01
  • 1970-01-01
  • 2011-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多