您是否知道使用redis客户端多重事务命令与bluebird承诺的方法?
因为,以下代码永远不会完成。
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();
});
答案 0 :(得分:2)
该命令不需要挂起的唯一事情就是在之前使用promisified连接获取多个。
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();
});
答案 1 :(得分:1)
有没有办法在这些块完成后运行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
完成后执行它,那么它将是
$r.pfaddAsync('key', item)
.then(function(result) {
return $r.incrAsync(result === 0 ? 'dup' : 'unq');
// ^^^^^^
})
.then($r.exec);
当.then($r.exec)
需要作为方法调用时,exec
可能无效,请改用<{1}}