node.js - 使用 util.promisify 模拟 bluebird.promisifyAll

标签 node.js typescript redis promise bluebird

我正在尝试 promise 整个 node_redis RedisClient 对象使用 Node 8 的 util.promisify 的方式类似于 Bluebird 的 promisifyAll() 的工作方式,但运气不佳。

这是我迄今为止尝试过的:

import * as _redis from 'redis';
import { promisify } from 'util';
const client = _redis.createClient();
const redis = Object.keys(client).reduce((c, key) => {
  if (typeof c[key] === 'function') c[key] = promisify(c[key]).bind(c);
  return c;
}, client);

然而,这有效:

const redis = {
  get: promisify(client.get).bind(client),
  set: promisify(client.set).bind(client),
  hget: promisify(client.hget).bind(client),
  hmset: promisify(client.hmset).bind(client),
};

有什么想法吗?

编辑:我想使用 util.promisify 而不是像 Bluebird 这样的东西的主要原因是因为我在 TypeScript 中做这一切,而 Bluebird 的 promisifyAll 似乎不适用于此。

最佳答案

我在寻找同样的东西时遇到了这个。这是我目前正在使用的,它似乎有效:

const { promisify } = require('util')
const redis = require('redis')

const client = redis.createClient('redis://localhost:6379')

client.promise = Object.entries(redis.RedisClient.prototype)
  .filter(([_, value]) => typeof value === 'function')
  .reduce((acc, [key, value]) => ({
    ...acc,
    [key]: promisify(value).bind(client)
  }), {})

client.on('connect', async () => {
  await client.promise.set('foo', 'bar')

  console.log(await client.promise.get('foo'))
})

关于node.js - 使用 util.promisify 模拟 bluebird.promisifyAll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45566289/

相关文章:

node.js - Handlebars 作为电子邮件模板

node.js - GCF Node10 部署失败 : "Function failed on loading user code. Error message: Provided code is not a loadable module."

node.js - 在前台启动 redis 并使用一个命令并行但串行地启动 Node 服务器

node.js - 将路由参数传递给 Mongoose Query Express

javascript - "msg":"Error parsing JSON field value. 意外的 OBJECT_START

typescript - Jasmine-ts 抛出关于包子路径的错误

javascript - 如何将 Luxon DateTime 格式转换为字符串或数字?

html - Mat-slide-toggle 看起来像普通复选框

php - 使用 Redis 缓存 Eloquent 模型实例

servlets - jedis 在 servlet 中的使用