gpt4 book ai didi

javascript - 在构造方法中初始化 Promises 类字段

转载 作者:行者123 更新时间:2023-11-30 19:30:11 25 4
gpt4 key购买 nike

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

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 类型,构造函数是一个 sincronous 方法,那么,我该如何让构造函数初始化这个字段?

谢谢

最佳答案

你可以这样考虑:

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

关于javascript - 在构造方法中初始化 Promises 类字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56507237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com