Skip to content

Instantly share code, notes, and snippets.

@dontpaniclabsgists
Created January 17, 2025 14:35
Show Gist options
  • Save dontpaniclabsgists/da4aefaf241c1480547e74e13f19cfc8 to your computer and use it in GitHub Desktop.
Save dontpaniclabsgists/da4aefaf241c1480547e74e13f19cfc8 to your computer and use it in GitHub Desktop.
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