Skip to content

Instantly share code, notes, and snippets.

@TheYarin
Last active February 3, 2022 17:11
Show Gist options
  • Save TheYarin/c3c57ba58eb9ed4a8752babe5b7e3215 to your computer and use it in GitHub Desktop.
Save TheYarin/c3c57ba58eb9ed4a8752babe5b7e3215 to your computer and use it in GitHub Desktop.
A cute typescript async lock class I scribbled down
// You can either use lock() and get a function that releases the lock, or you could use lockAndRun() to wrap around a function! Amazing!
class AsyncLock {
private promises = new Map<string, Promise<void>>();
public async lock(key: string): Promise<VoidFunction> {
if (this.promises.has(key)) {
await this.promises.get(key);
}
let release: VoidFunction;
const lockPromise = new Promise<void>(resolve => {
release = () => {
resolve();
this.promises.delete(key);
};
});
this.promises.set(key, lockPromise);
return release!;
}
public async lockAndRun<R, F extends () => Promise<R>>(key: string, fn: F): Promise<R> {
const release = await this.lock(key);
try {
return await fn();
} finally {
release();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment