在构造函数方法中初始化Promises类字段

时间:2019-06-08 14:21:17

标签: javascript typescript typeorm

我在这里用存储库做了一个测试,这就是测试:

export default class UserService {
    private userRepository: Repository<UserModel>;
    private connection: Connection;

    private async initialize(): Promise<any> {
        return createConnection()
        .then(v => this.connection = v)
        .then(_ => this.userRepository = this.connection.getRepository(UserModel))
      }

    constructor() {
    }

    public async findByUsername(username: string): Promise<UserModel> {
        let user: any;

        if(this.userRepository == undefined) {
            await this.initialize();
        }

        await this.userRepository.findOne({username: username}).then(v => user = v);
        return user;
    }

}

它正在工作,但是lint / TS编译器在说:类字段userRepository和连接未在构造函数方法中初始化。

好的,但是这个字段是Promise类型的,而构造函数是一个很自然的方法,那么,如何构造函数初始化这个字段?

谢谢

1 个答案:

答案 0 :(得分:1)

您可以考虑这样的事情:

export default class UserService {
  private connection: Promise<Connection> = createConnection();
  private userRepository: Promise<Repository<UserModel>> = this.connection.then(c =>
    c.getRepository(UserModel),
  );

  public async findByUsername(username: string): Promise<UserModel> {
    const userRepository = await this.userRepository;

    return await userRepository.findOne({ username });
  }
}