Fix race condition in that code class DummyClient { async connect() { return new…
- User
Fix race condition in that code class DummyClient { async connect() { return new Promise(resolve => { setTimeout(() => { console.log(‘connect’); resolve(0) }, 2000); }) } async doSomething() { console.log(‘done something’) }}class ApiWrapper { #client = null; async getClient() { if (!this.loaded) { const client = new DummyClient(); await client.connect(); this.#client = client; return this.#client; } return this.#client; } get loaded() { return !!this.#client; } async doSomething() { if (!this.loaded) await this.getClient(); return this.#client.doSomething(); }}const run = async () => { const api = new ApiWrapper(); await Promise.all([api.doSomething(), api.doSomething(), api.doSomething(), api.doSomething()]);}run();
- Assistant
To fix the race condition in the code, you can modify the
getClient()method in theApiWrapperclass to use a lock to ensure that only one connection attempt is made at a time. Here's an updated version of the code with the race condition fixed:javascript