Skip to content

Instantly share code, notes, and snippets.

@Raynos
Last active June 9, 2020 15:43
Show Gist options
  • Save Raynos/37a7ffd11c5ff0dcc94ccb609459226f to your computer and use it in GitHub Desktop.
Save Raynos/37a7ffd11c5ff0dcc94ccb609459226f to your computer and use it in GitHub Desktop.
PromiseLock or Mutex ?
/**
* 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