如何正确处理打字稿中的promisifyAll?

时间:2016-04-12 03:23:02

标签: javascript typescript promise bluebird

请考虑以下代码:

import redis = require('redis');  //Has ambient declaration from DT
import bluebird = require('bluebird');  //Has ambient declaration from DT

bluebird.promisifyAll((<any>redis).RedisClient.prototype);
bluebird.promisifyAll((<any>redis).Multi.prototype);

const client = redis.createClient();

client.getAsync('foo').then(function(res) {
    console.log(res);
});

getAsync会出错,因为它是动态创建的,并且未在任何.d.ts文件中定义。那么处理这个问题的正确方法是什么?

此外,即使我为redis加载了.d.ts个文件,我仍然需要将redis投射到any以用于promisifyAll。否则,它会溢出错误:

Property 'RedisClient' does not exist on type 'typeof "redis"'

输入any唯一简单的方法吗?

3 个答案:

答案 0 :(得分:6)

我是通过declaration merging setAsync&amp; getAsync方法。我在自己的自定义.d.ts文件中添加了以下代码。

declare module "redis" {

    export interface RedisClient extends NodeJS.EventEmitter {
        setAsync(key:string, value:string): Promise<void>;
        getAsync(key:string): Promise<string>;
    }

}

答案 1 :(得分:1)

只需添加Dave的答案,就我的需要而言,我必须添加Multi来进行原子操作。

declare module 'redis' {
    export interface RedisClient extends NodeJS.EventEmitter {
        execAsync(...args: any[]): Promise<any>;
        hgetallAsync(...args: any[]): Promise<any>;
        // add other methods here
    }
    export interface Multi extends Commands<Multi> {
        execAsync(...args: any[]): Promise<any>;
        // add other methods here
    }
}

答案 2 :(得分:0)

另一种需要较少代码的方法是像这样扩展Redis对象:

import { promisify } from 'util';
import { ClientOpts, RedisClient } from 'redis';

class AsyncRedis extends RedisClient {
  public readonly getAsync = promisify(this.get).bind(this);
  public readonly setAsync = promisify(this.set).bind(this);
  public readonly quitAsync = promisify(this.quit).bind(this);
  public readonly rpushAsync: (list: string, item: string) => Promise<number> = promisify(
    this.rpush
  ).bind(this);
  public readonly blpopAsync: (
    list: string,
    timeout: number
  ) => Promise<[string, string]> = promisify(this.blpop).bind(this);
  public readonly flushdbAsync = promisify(this.flushdb).bind(this);
}

请注意,并非所有方法签名都能正确覆盖,因此您需要稍微帮助打字稿。

现在,您可以通过使用选项创建它来使用此增强的类,例如:

new AsyncRedis({
  host: process.env.REDIS_HOST || '127.0.0.1',
  password: process.env.REDIS_PASSWORD || 'whatever',
 });