r/javascript • • 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

13 comments sorted by

View all comments

3

u/TiddoLangerak Aug 16 '24

It's an interesting solution! Isn't it leaky though? I.e. the entire promise chain is kept for the lifetime of the mutex, so if the mutex lives long enough and is used often enough then this could cause memory issues.