我试图用类似于Bluebird的node_redis工作的方式使用Node 8的RedisClient
来宣传整个util.promisify
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'))
})
你可以使用fluentify,它很小,没有外部依赖,几乎可以做你的追求。我实际上是将它自己用于Redis,有一些小的警告,但在你的情况下应该相当简单,例如
import * as _redis from 'redis';
import fluentify from 'fluentifyjs';
...
const client = fluentify(_redis.createClient());
const result = await client.get('key').done();
我得到你可能希望本地做这件事,然而,认为作为一种替代方案值得一提,考虑到如果需要你可以免费获得方法链接。
免责声明 - 我是作者