【问题标题】:Redis multi with bluebird promises带有蓝鸟承诺的 Redis multi
【发布时间】:2014-12-07 02:29:13
【问题描述】:

您知道将 redis 客户端的多事务命令与 bluebird Promise 一起使用的方法吗?

因为,下面的代码永远不会结束。

  var $redis = require('redis'),
      $p = require('bluebird'),
      $r = $p.promisifyAll($redis.multi());

  $r.setAsync('key', 'test')
    .then(function(reply, data) {
      // ...
    });

  $r.exec(function() {
    $r.quit();
    process.exit();
  });

【问题讨论】:

    标签: node.js redis promise bluebird


    【解决方案1】:

    命令不挂起唯一需要的就是在之前使用承诺连接获得 multi。

    var $redis = require('redis'),
        $p = require('bluebird'),
        $r;
    
    // this is important for bluebird async operations!
    $r = $p.promisifyAll($redis.createClient.apply(this, arguments));
    
    // multi also need to be promisifed with the promisified conn above
    $r = $p.promisifyAll($r.multi());
    
    $r.setAsync('key', '0').then(function(data) { });
    $r.incrAsync('key');
    
    // all of the above commands pipelined above will be executed with this command
    $r.execAsync().then(function() {
      $r.quit();
    
      // this will make the console app (or whatever app) quit
      process.exit();
    });
    

    【讨论】:

      【解决方案2】:

      有没有办法在这些块完成后运行 exec?

      嗯,把它锁起来:

      $r.pfaddAsync('key', item)
        .then(function(result) {
          // marked
          if (result === 0) {
            $r.incrAsync('dup');
          } else {
            $r.incrAsync('unq');
          }
          $r.exec();
        });
      

      甚至可能

      $r.pfaddAsync('key', item)
        .then(function(result) {
          // marked
          if (result === 0) {
            $r.incrAsync('dup');
          } else {
            $r.incrAsync('unq');
          }
        })
        .then($r.exec);
      

      或者,如果你想在incrAsyncs 完成之后执行它,那么它会是

      $r.pfaddAsync('key', item)
        .then(function(result) {
          return $r.incrAsync(result === 0 ? 'dup' : 'unq');
      //  ^^^^^^
        })
        .then($r.exec);
      

      exec 需要作为方法调用时,.then($r.exec) 可能不起作用,请改用.then($r.exec.bind($r))

      【讨论】:

      • 非常感谢。有没有更优雅的解决方案?如果有人还需要在 $r.pfaddAsync 之后添加更多命令并且与 pfaddAsync 无关但最后应该调用 $r.exec 怎么办?
      • 不,then 已经很优雅了。如果您想调用多个独立的异步函数并希望等待所有这些函数(在继续使用$r.exec 之前),您可以使用Promise.all
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 2014-11-06
      • 2015-09-06
      • 2015-02-13
      相关资源
      最近更新 更多