Last active
February 3, 2022 17:11
-
-
Save TheYarin/c3c57ba58eb9ed4a8752babe5b7e3215 to your computer and use it in GitHub Desktop.
A cute typescript async lock class I scribbled down
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
// 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