TypeScript class instance not behaving as expected when using async methods
I'm trying to figure out I'm working with an scenario where the instance of a TypeScript class does not behave as expected when I introduce asynchronous methods. I have a class that fetches data from an API, and I want to ensure that when one of its methods is called, it waits for the async operation to complete before proceeding. Here's a simplified version of my code: ```typescript class DataFetcher { private data: any; constructor() { this.data = null; } async fetchData(url: string): Promise<void> { const response = await fetch(url); this.data = await response.json(); } async getData(): Promise<any> { if (!this.data) { console.log('Fetching data...'); await this.fetchData('https://api.example.com/data'); } console.log('Returning data:', this.data); return this.data; } } const fetcher = new DataFetcher(); fetcher.getData().then(data => console.log(data)); ``` The question arises when I try to call `getData` multiple times in rapid succession. I expect it to fetch the data only once and return the cached result on subsequent calls. However, I see multiple logs of 'Fetching data...' and possibly inconsistent states of `data`. I tried adding some console logs to track the flow and it seems that the async nature causes issues when multiple calls to `getData` are made before the data has been fetched. Is there a better way to handle this situation to ensure that subsequent calls to `getData` wait for the initial fetch to complete, especially when dealing with rapid invocations? I also want to ensure that this pattern is performant and avoids unnecessary API calls. Any guidance or best practices would be greatly appreciated! I'm working on a web app that needs to handle this. Any help would be greatly appreciated!