Options
All
  • Public
  • Public/Protected
  • All
Menu

Class AsyncLock

A namespaced Semaphore for asynchronous operations.

Not providing a key to the methods makes this function as if it were a normal Semaphore.

example

const lock = new AsyncLock();

async function write(text: string, key: string, delay?: number): Promise<void> {
     await lock.withLock(async () => {
         // wait 500ms
         await new Promise(res => setTimeout(res, 500 + (delay || 0)));
         console.info(text);
     }, key);
}

// these operations will practically start at the same time!
// but there will be a 500ms delay between write calls of the same key

write("this", "a");
write("is", "a");
write("me", "a", 10);

write("cute", "b");
write("not", "b");
write("loyal", "b");

write("dog", "c");
write("very", "c");
write("to", "c");

// Output:
// *500ms pass*
// this cute dog
// *500ms pass*
// is not very
// *500ms pass*
// loyal to me

Hierarchy

  • AsyncLock

Index

Constructors

constructor

Properties

Private locked

locked: Set<any>

Private queues

queues: Map<any, Array<function>>

Methods

acquire

  • acquire(...keys: any[]): Promise<void>
  • Wait for the keys to be unlocked and lock them. Don't forget to call AsyncLock.release with the same arguments!

    see

    AsyncLock.withLock for a safer and more convenient approach.

    Parameters

    • Rest ...keys: any[]

    Returns Promise<void>

Private getQueue

  • getQueue(key: any): Array<function>
  • Parameters

    • key: any

    Returns Array<function>

isLocked

  • isLocked(...keys: any[]): boolean
  • Check whether the given key is locked.

    If provided with multiple keys it checks whether any of the keys are locked.

    Parameters

    • Rest ...keys: any[]

    Returns boolean

release

  • release(...keys: any[]): void
  • Unlock the given key(s). This method should only be called by the code that previously called AsyncLock.acquire

    see

    AsyncLock.withLock for a safer and more convenient approach.

    Parameters

    • Rest ...keys: any[]

    Returns void

Private shiftQueue

  • shiftQueue(key: any): void
  • Parameters

    • key: any

    Returns void

Private waitForLocked

  • waitForLocked(key: any): Promise<void>
  • Wait and lock the specified key.

    see

    AsyncLock.acquire for a high-level method.

    Parameters

    • key: any

    Returns Promise<void>

withLock

  • Perform an action using the lock and then release it again. This method always calls AsyncLock.release but doesn't silence any errors.

    The provided keys are interpreted the same as for AsyncLock.acquire.

    Type parameters

    • T

    Parameters

    Returns Promise<T>

Generated using TypeDoc