Created
January 17, 2025 14:34
-
-
Save dontpaniclabsgists/7de62ef62b650cf5b5b722e59d8c53ce to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
loadWithPromiseLock = async (key: string): Promise<boolean> => { | |
this.log(key + 'Calling loadWithPromiseLock'); | |
const random = Math.random(); | |
this.log(key + 'Random: ' + random); | |
// Check if the data is already loaded | |
if (this.promiseDataMap.has(key)) { | |
this.log(key + 'Data is already loaded'); | |
return true; | |
} | |
// Check if there is already a loading promise for this key | |
if (this.fallbackLoadingPromises.has(key)) { | |
this.log(key + 'Data is already loading'); | |
return this.fallbackLoadingPromises.get(key)!; | |
} | |
// Create a new loading promise | |
const loadingPromise = (async () => { | |
this.log(key + '***START*** Loading data'); | |
await this.slowApiCall(key); | |
this.promiseDataMap.set(key, 'data + ' + random); | |
// Remove the loading promise from the map after completion | |
this.fallbackLoadingPromises.delete(key); | |
this.log(key + '***END*** Data loaded'); | |
return true; | |
})(); | |
// Store the loading promise in the map | |
this.fallbackLoadingPromises.set(key, loadingPromise); | |
return loadingPromise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment