Last active
June 9, 2020 15:43
-
-
Save Raynos/37a7ffd11c5ff0dcc94ccb609459226f to your computer and use it in GitHub Desktop.
PromiseLock or 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
/** | |
* A PromiseLock like object. | |
* | |
* Used to ensure that we only do one thing at a time on a shared resource. | |
* | |
* For example, with async iterator: | |
* | |
* this.readLock = new Mutex() | |
* this.readLock.do(async () => { | |
* const data = await itr.next(); | |
* // do stuff with itr result | |
* }) | |
* | |
* Allows for handling resources that are not concurrency friendly in order. | |
*/ | |
class Mutex { | |
constructor () { this.pendingOperation = null } | |
async do (operation) { | |
if (this.pendingOperation) await this.pendingOperation | |
if (this.pendingOperation) return this.do(operation) | |
const promise = operation() | |
this.pendingOperation = promise | |
const result = await promise | |
this.pendingOperation = null | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment