X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils%2FAsyncLock.ts;h=fe984cebdef97d8043d0f29f6fb9ba99ec502f3c;hb=ab7a96fac9432c4759e0bb69a12bb481b1570e02;hp=b396e49b50901fae636f565198f73dddc0b58c09;hpb=e1d9a0f4d6ff1a90048e9a694fd12b7031cc6961;p=e-mobility-charging-stations-simulator.git diff --git a/src/utils/AsyncLock.ts b/src/utils/AsyncLock.ts index b396e49b..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,25 +21,33 @@ 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; return; } - return new Promise((resolve) => { + return new Promise((resolve) => { asyncLock.resolveQueue.enqueue(resolve); }); } - 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; return; } const queuedResolve = asyncLock.resolveQueue.dequeue()!; - return new Promise((resolve) => { + return new Promise((resolve) => { queuedResolve(); resolve(); });