Skip to main content

Mutex

Mutex maintains a queue of Promise-returning functions that are executed sequentially (whereas normally they would execute their async code concurrently).

Implements

Constructors

Constructor

new Mutex(): Mutex;

Returns

Mutex

Methods

batched()

batched<T, R>(process, options?): (items) => Promise<R[]>;

Transform a function into a queued batch processor.

Type Parameters

Type Parameter
T
R

Parameters

ParameterTypeDescription
process(items) => Promise<R[]>The processing function. It takes a batch of items, and must return the same number of results.
options?{ debounce?: number; limit?: number; }-
options.debounce?numberSpecify to add a delay between queuing a batch and processing the batch.
options.limit?numberAn optional limit to the number of items passed to a single batch.

Returns

(items) => Promise<R[]>


exclusiveLock()

exclusiveLock<T>(promiseFn): Promise<T>;

Place a function on the queue. The function may either return a Promise or a value. Return a Promise that is resolved with the result of the function.

Type Parameters

Type Parameter
T

Parameters

ParameterType
promiseFnPromiseFunction<T>

Returns

Promise<T>

Implementation of

MutexContext.exclusiveLock


isFree()

isFree(): boolean;

Returns true if no locks are held: the queue is empty, and no tasks are being executed.

Returns

boolean


qu()

qu<T>(fn): T;

Convert a normal Promise-returning function into one that is automatically enqueued. The signature of the function stays the same - only the execution is potentially delayed. The only exception is that if the function would have returned a scalar value, it now returns a Promise.

Type Parameters

Type Parameter
T extends (...args) => Promise<any>

Parameters

ParameterType
fnT

Returns

T


quOnce()

quOnce<T>(fn): T;

Like qu, but ensures there is never more than one function on the queue. Note that there may be one running as well as one on the queue.

If a call to this function would result in a second item on the queue, the last promise this returned. In that case, any arguments passed to the function are ignored.

Type Parameters

Type Parameter
T extends (...args) => Promise<any>

Parameters

ParameterType
fnT

Returns

T


sharedLock()

sharedLock<T>(promiseFn): Promise<T>;

Place a function on the queue. This function may execute in parallel with other "multi" functions, but not with other functions on the exclusive queue.

Type Parameters

Type Parameter
T

Parameters

ParameterType
promiseFnSharedPromiseFunction<T>

Returns

Promise<T>

Implementation of

MutexContext.sharedLock


waitUntilFree()

waitUntilFree(): Promise<void>;

Resolves when no lock is being held: the queue is empty, and no tasks are being executed.

Returns

Promise<void>