Skip to content

Instantly share code, notes, and snippets.

@artursapek
Created June 2, 2016 16:23
Show Gist options
  • Save artursapek/70437f6cdb562b7b62e910fd33ee8554 to your computer and use it in GitHub Desktop.
Save artursapek/70437f6cdb562b7b62e910fd33ee8554 to your computer and use it in GitHub Desktop.
// Originally taken from https://github.com/mgtitimoli/await-mutex
class Mutex {
constructor() {
this._locking = Promise.resolve();
this._locked = false;
}
isLocked() {
return this._locked;
}
lock() {
this._locked = true;
let unlockNext;
let willLock = new Promise(resolve => unlockNext = resolve);
willLock.then(() => this._locked = false);
let willUnlock = this._locking.then(() => unlockNext);
this._locking = this._locking.then(() => willLock);
return willUnlock;
}
}
export default Mutex;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment