我有一个redis util,看起来像:

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

编辑2:也许这有效(如果不是没有宣传功能的一些奇怪的副作用,我可能不需要/想要宣传?)

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