node-redis promisification 使用 bluebird

node-redis promisification using bluebird

我正在尝试将 promises 与 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();
  });
});

但我被下面的那个卡住了,我怎么能承诺呢?

// 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();
  });
});

client.on() 方法来自 EventEmitter 原型,redis 客户端可能继承自该原型。您可以尝试遍历原型链并对其进行 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();
    });
  });
});

像 Freyday siad,on 不是异步方法,而是一个事件发射器,所以我强烈建议您不要承诺它,但是嘿,如果您坚持要这样做,您可以这样做:

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 promise。例如:

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