使用Node.js util模块实现所有方法的承诺

时间:2018-12-08 19:53:25

标签: javascript ecmascript-6

我有一个redis实用程序,看起来像:

const redis = require('redis')
const { promisify } = require('util')
const client = redis.createClient({
  host: '127.0.0.1',
  port: '6379'
})

module.exports = {
  get: promisify(client.get).bind(client),
  hget: promisify(client.hget).bind(client),
  set: promisify(client.set).bind(client),
  mset: promisify(client.mset).bind(client),
  hset: promisify(client.hset).bind(client),
  hmset: promisify(client.hmset).bind(client),
  ...
}

我想重写所有内容。如何在每个方法上迭代promisify来导出客户端函数?

最初,我以Object.keys(client)Object.getOwnPropertyNames(client)作为抓取要映射的方法名称的起点,但是这些数组都不包含它们。

编辑:这更接近了,有没有更好的方法来表达这一点?

const promisifiedClient = {}

for (const fn in Object.getPrototypeOf(client)) {
  if (typeof client[fn] === 'function') {
    promisifiedClient[fn] = promisify(client[fn]).bind(client)
  }
}

module.exports = promisifiedClient

Edit2:也许这行得通(如果不是我可能不需要/不想传播的有混杂功能的奇怪副作用的话)

const redisFunctionList = Object.keys(Object.getPrototypeOf(client))

const promisifiedRedis = redisFunctionList.reduce((acc, functionName) => {
  acc[functionName] = promisify(client[functionName]).bind(client)
  return acc
}, {})

module.exports = promisifiedRedis

1 个答案:

答案 0 :(得分:0)

您可以使用 bluebird 包,然后可以简单地承诺 redis 客户端。

const redis = require("redis");
const bluebird = require("bluebird");
const client = new redis.RedisClient();

/// promise based client of redis
/// storing it in a variable helps with intellisense
const promiseClient = bluebird.promisifyAll(client);

const main = async () => {
  /// After that, we just call the default methods with an Async in the end
  /// For Example:
  /// client.get becomes client.getAsync
  /// client.set becaomes client.setAsync
  const data = await promiseClient.getAsync("foo");
  console.log(data);
  const message = await promiseClient.quitAsync();
  console.log(message);
};

main();

module.exports = promiseClient;