Skip to content

Instantly share code, notes, and snippets.

@slmyers
Forked from artursapek/mutex.js
Last active June 2, 2016 18:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slmyers/94cb89739271a007e118d294edc64f75 to your computer and use it in GitHub Desktop.
Save slmyers/94cb89739271a007e118d294edc64f75 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;
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