r/javascript • u/ccjsml • Aug 16 '24
AskJS [AskJS] The most simplest Javascript mutex implementation in the world.
I don't think you can find a version simpler than this.
export class Mutex {
private mutex = Promise.resolve();
lock(): Promise<() => void> {
return new Promise((resolve) => {
this.mutex = this.mutex.then(() => new Promise(resolve));
});
}
}To use it, do
mutex = new Mutex();
const unlock = await mutex.lock();
try {
// do something...
} finally {
unlock();
}
1
Upvotes
14
u/Badashi Aug 16 '24
While I do like how elegant it is, browsers have nice implementation called Web Locks API. For node, you can install web-locks since it doesn't have a native api by itself.
Not that I dislike your implementation, I love some elegant solution like that; but I personally prefer the WebLocks API because we don't need to rely on try/catch and we can use AbortSignal if needed.