Created
June 2, 2016 16:23
-
-
Save artursapek/70437f6cdb562b7b62e910fd33ee8554 to your computer and use it in GitHub Desktop.
This file contains 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
// 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