X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FAsyncLock.ts;h=fe984cebdef97d8043d0f29f6fb9ba99ec502f3c;hb=365cc3b83e3ae98a510608e25b341f9e6d6cfbe1;hp=9c0584565e3ecb80897b2ad32418a1afdb0cc888;hpb=474d4ffcd45d49bb242f51510a28569b00328676;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/AsyncLock.ts b/src/utils/AsyncLock.ts index 9c058456..fe984ceb 100644 --- a/src/utils/AsyncLock.ts +++ b/src/utils/AsyncLock.ts @@ -2,6 +2,8 @@ import Queue from 'mnemonist/queue.js'; +import { Constants } from './Constants'; + export enum AsyncLockType { configuration = 'configuration', performance = 'performance', @@ -19,7 +21,15 @@ export class AsyncLock { this.resolveQueue = new Queue(); } - public static async acquire(type: AsyncLockType): Promise { + public static async runExclusive(type: AsyncLockType, fn: () => T | Promise): Promise { + return AsyncLock.acquire(type) + .then(fn) + .finally(() => { + AsyncLock.release(type).catch(Constants.EMPTY_FUNCTION); + }); + } + + private static async acquire(type: AsyncLockType): Promise { const asyncLock = AsyncLock.getAsyncLock(type); if (!asyncLock.acquired) { asyncLock.acquired = true; @@ -30,7 +40,7 @@ export class AsyncLock { }); } - public static async release(type: AsyncLockType): Promise { + private static async release(type: AsyncLockType): Promise { const asyncLock = AsyncLock.getAsyncLock(type); if (asyncLock.resolveQueue.size === 0 && asyncLock.acquired) { asyncLock.acquired = false;