Options
All
  • Public
  • Public/Protected
  • All
Menu

Class IMQLock

Class IMQLock. Implements promise-based locks.

example
import { IMQLock, AcquiredLock } from '.';

async function doSomething(): Promise<number | AcquiredLock<number>> {
    const lock: AcquiredLock<number> = await IMQLock.acquire<number>('doSomething');

    if (IMQLock.locked('doSomething')) {
        // avoiding err handling in this way can cause ded-locks
        // so it is good always try catch locked calls!
        // BTW, IMQLock uses timeouts to avoid dead-locks
        try {
            // this code will be called only once per multiple async calls
            // so all promises will be resolved with the same value
            const res = Math.random();
            IMQLock.release('doSomething', res);
            return res;
        }

        catch (err) {
             // release acquired locks with error
            IMQLock.release('doSomething', null, err);
            throw err;
        }
    }

    return lock;
}

(async () => {
    for (let i = 0; i < 10; ++i) {
        // run doSomething() asynchronously 10 times
        doSomething().then((res) => console.log(res));
    }
})();

Hierarchy

  • IMQLock

Index

Properties

Static deadlockTimeout

deadlockTimeout: number = 10000

Deadlock timeout in milliseconds

type

{number}

Static logger

logger: ILogger = console

Logger used to log errors which appears during locked calls

type

{ILogger}

Methods

Static acquire

  • acquire<T>(key: string, callback?: undefined | function): Promise<AcquiredLock<T>>
  • Acquires a lock for a given key

    Type parameters

    • T

    Parameters

    • key: string
    • Optional callback: undefined | function

    Returns Promise<AcquiredLock<T>>

Static locked

  • locked(key: string): boolean
  • Returns true if given key is locked, false otherwise

    Parameters

    • key: string

    Returns boolean

Static release

  • release<T, E>(key: string, value?: T, err?: E): void
  • Releases previously acquired lock for a given key

    Type parameters

    • T

    • E

    Parameters

    • key: string
    • Optional value: T
    • Optional err: E

    Returns void