diff --git a/src/Mutex.ts b/src/Mutex.ts index 87d83c3..04cb48b 100644 --- a/src/Mutex.ts +++ b/src/Mutex.ts @@ -16,6 +16,10 @@ class Mutex implements MutexInterface { return this._semaphore.runExclusive(() => callback()); } + wrap(func: Function): Function { + return this._semaphore.wrap(func); + } + isLocked(): boolean { return this._semaphore.isLocked(); } diff --git a/src/Semaphore.ts b/src/Semaphore.ts index 6456155..cb4716e 100644 --- a/src/Semaphore.ts +++ b/src/Semaphore.ts @@ -36,6 +36,14 @@ class Semaphore implements SemaphoreInterface { } } + wrap(func: Function): Function { + return new Proxy(func, { + apply: (target, that, args) => { + return this.runExclusive(() => Promise.resolve(target.apply(that, args))); + }, + }); + } + isLocked(): boolean { return this._value <= 0; }