Mutex.js 467 B

123456789101112131415161718192021222324
  1. export class Mutex {
  2. constructor () {
  3. this._locked = false
  4. this._waiting = []
  5. }
  6. lock () {
  7. const unlock = () => {
  8. const next = this._waiting.shift()
  9. if (next) {
  10. next(unlock)
  11. } else {
  12. this._locked = false
  13. }
  14. }
  15. if (this._locked) {
  16. return new Promise(resolve => this._waiting.push(resolve)).then(() => unlock)
  17. } else {
  18. this._locked = true
  19. return Promise.resolve(unlock)
  20. }
  21. }
  22. }