Node.js Redis multi与蓝鸟承诺
您知道如何将redis客户端的多事务命令与bluebird promises一起使用吗 因为,下面的代码永远不会结束Node.js Redis multi与蓝鸟承诺,node.js,redis,promise,bluebird,Node.js,Redis,Promise,Bluebird,您知道如何将redis客户端的多事务命令与bluebird promises一起使用吗 因为,下面的代码永远不会结束 var $redis = require('redis'), $p = require('bluebird'), $r = $p.promisifyAll($redis.multi()); $r.setAsync('key', 'test') .then(function(reply, data) { // ... }
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();
});
有没有办法在这些块完成后运行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);
或者,如果要在
incrAsync
s完成后执行它,则
$r.pfaddAsync('key', item)
.then(function(result) {
return $r.incrAsync(result === 0 ? 'dup' : 'unq');
// ^^^^^^
})
.then($r.exec);
.then($r.exec)
可能不起作用。当需要将exec
作为方法调用时,请使用。然后($r.exec.bind($r))
改为命令不挂起所需的唯一一件事是在之前获得具有预期连接的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();
});
非常感谢你。还有更优雅的解决方案吗?如果有人还需要在$r.pfaddAsync之后添加更多命令,并且与pfaddAsync无关,但最终应该调用$r.exec,该怎么办?不,
那么
已经相当优雅了。如果要调用多个独立的异步函数并等待所有函数(在继续执行$r.exec
之前),可以使用