-
-
Save slmyers/94cb89739271a007e118d294edc64f75 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; |
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
import Mutex from 'lib/mutex'; | |
class MyObject { | |
constructor() { | |
this.m = new Mutex(); | |
} | |
async someNetworkCall() { | |
let unlock = await this.m.lock(); | |
doSomethingAsynchronous().then((result) => { | |
// handle result | |
unlock(); | |
}).catch((err) => { | |
// handle error | |
unlock(); | |
}); | |
} | |
} | |
let mo = new MyObject(); | |
mo.someNetworkCall(); | |
// The next call will wait until the first call is finished | |
mo.someNetworkCall(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment