Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emulating bluebird.promisifyAll with util.promisify

I'm trying to promisify the entire node_redis RedisClient object using Node 8's util.promisify in a manner similar to how Bluebird's promisifyAll() works, and not having much luck.

This is what I've tried thus far:

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);

This, however, works:

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),
};

Any ideas?

edit: The main reason I'm wanting to use util.promisify instead of something like Bluebird is because I'm doing this all in TypeScript, and Bluebird's promisifyAll doesn't seem to work with that.

like image 675
aendra Avatar asked Aug 08 '17 10:08

aendra


1 Answers

Came across this as I was looking for a same thing. This is what I'm using currently and it seems to work:

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'))
})
like image 50
Yliaho Avatar answered Nov 09 '22 09:11

Yliaho