Я бы сделал как-то так, но метод connect обертки у меня явно костыльный, т.к., имхо, хранить состояние соединения должен сам клиент, а не пытаться открыть соединение на каждый вызов метода `connect`:
interface IClient {
connect(): Promise<void>;
doSomething(): Promise<void>;
}
declare const DummyClient: new() => IClient;
class ApiWrapper {
#client!: IClient;
#connectionPromise: Promise<void> | null = null;
#connectionState: 'connected' | 'connecting' | 'disconnected' = 'disconnected';
constructor(client?: IClient) {
this.#client = client ?? new DummyClient();
}
async connect() {
if (this.#connectionState !== 'disconnected') {
return this.#connectionPromise;
}
this.#connectionState = 'connecting';
return this.#connectionPromise = this.#client.connect().then(v => {
this.#connectionState = 'connected';
return v;
}).catch(e => {
this.#connectionState = 'disconnected';
throw e;
});
}
async doSomething() {
await this.connect();
return this.#client.doSomething();
}
}
ts playground