@x5e/gink
Version:
an eventually consistent database
37 lines • 1.33 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PromiseChainLock = void 0;
class PromiseChainLock {
constructor() {
// Chain of promises that allow multiple attempts to acquire to wait their turn for the lock.
this.queue = Promise.resolve();
}
/**
* An async function that waits to acquire the lock, then provides a function to unlock.
* Use like:
* const unlockingFunction = await promiseChainLock.acquireLock();
* try {
* // Do some stuff.
* } finally {
* unlockingFunction();
* }
* @returns a promise that resolves when the lock has been acquired, resolving to a cb to unlock it.
*/
acquireLock() {
let calledWhenLockAcquired;
let calledToReleaseLock;
const resolvesWhenLockAcquired = new Promise((r) => {
calledWhenLockAcquired = r;
});
this.queue = this.queue.then(() => {
const resolvesWhenLockReleased = new Promise((r) => {
calledToReleaseLock = r;
});
calledWhenLockAcquired(calledToReleaseLock);
return resolvesWhenLockReleased;
});
return resolvesWhenLockAcquired;
}
}
exports.PromiseChainLock = PromiseChainLock;
//# sourceMappingURL=PromiseChainLock.js.map