Created
January 17, 2025 14:35
-
-
Save dontpaniclabsgists/da4aefaf241c1480547e74e13f19cfc8 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
import { Mutex } from 'async-mutex'; | |
private mutex = new Mutex(); | |
loadWithMutexLock = async (key: string): Promise<boolean> => { | |
this.log(key + 'Calling loadWithMutexLock'); | |
const random = Math.random(); | |
this.log(key + 'Random: ' + random); | |
// Check if the data is already loaded | |
if (this.mutexDataMap.has(key)) { | |
this.log(key + 'Data is already loaded'); | |
return true; | |
} | |
return this.mutex.runExclusive(async () => { | |
// Check again inside the mutex to avoid race conditions | |
if (this.mutexDataMap.has(key)) { | |
this.log(key + 'InsideMutex: Data is already loaded'); | |
return true; | |
} | |
this.log(key + '***START*** Loading data'); | |
await this.slowApiCall(key); | |
this.mutexDataMap.set(key, 'data + ' + random); | |
this.log(key + '***END*** Data loaded'); | |
return true; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment