节点redis promisification使用蓝鸟

我试图使用node-redis包的承诺,但我不能使用on.connect()方法。

var redis = require("redis"); var client = redis.createClient(); bluebird.promisifyAll(redis.RedisClient.prototype); bluebird.promisifyAll(redis.Multi.prototype); // callback version app.get('/redis', function(req, res) { client.set("foo_rand000000000000", "some fantastic value", function(err, reply) { if (err) { console.log(err); } else { console.log(reply); } res.end(); }); }); // promisified version app.get('/redis', function(req, res) { return client.setAsync("foo_rand000000000000", "some fantastic value").then(function(return) { console.log(return); // returns OK client.quit(); }); }); 

但是,我坚持下面的一个,我怎么能promisify呢?

 // example client.on("connect", function () { client.set("foo_rand000000000000", "some fantastic value", redis.print); client.get("foo_rand000000000000", redis.print); }); 

我尝试了下面的一个,但它不起作用,我看不到命令​​行上的响应:

 app.get('/redis', function(req, res) { return client.onAsync("connect").then(function(res) { console.log(res); res.end(); }); }); 

像Freyday siad,不是asynchronous方法,而是一个事件发射器,所以我强烈劝阻你不要冒用它,但是,嘿,如果你是狡猾的,你可以做这样的事情:

 let _connectResolve, _connectReject, onConnected = new Promise((resolve, reject) => { _connectResolve = resolve; _connectReject = reject; }), redis = require("redis"), client = redis.createClient(); client.on('connect', _connectResolve); // usage example: onConnected.then(() => { client.setAsync("foo_rand000000000000", "some fantastic value").then(redis.print); client.getAsync("foo_rand000000000000").then(redis.print); }); 

如果您担心的是,您必须等待客户端连接,然后才能获取/设置内容,则可以将所有呼叫链接到onConnected诺言。 例如:

 app.get('/redis', (req, res) => { onConnected .then(() => client.setAsync("foo_rand000000000000", "some fantastic value")) .then(() => res.end()); }); 

client.on()方法来自EventEmitter客户端可能inheritance的EventEmitter原型。 你可以试着走原型链,也可以把它作为promisify,但是我可能只是自己处理它而已:

 function onConnect(client) { return new Promise(function(resolve, reject) { client.on('connect', function(err) { if (err) return reject(err) return resolve() }) }) } 

那么你可以像这样使用它:

 app.get('/redis', function(req, res) { return onConnect(client) .then(function() { return client.setAsync("foo_rand000000000000", "some fantastic value") }) .then(function(result) { console.log(result); // returns OK client.quit(); res.end(); }); }); });