UNPKG

node-apparatus

Version:

A mix of common components needed for awesome node experience

62 lines (61 loc) 2.43 kB
import { SpinWaitLock } from "../spin-wait-lock/spin-wait-lock"; /** * A type that can be serialized. */ export type Serializable = string | number | boolean | Serializable[] | { [key: string]: Serializable; }; export interface InvocationResult<Treturn> { result?: Treturn; state: "success" | "error:queue-empty" | "error:queue-full"; } /** * A class that allows for the sequential invocation of a function. */ export declare class SequentialInvocationQueue<Targs extends Serializable, Treturn extends Serializable | void> { private readonly lock; private readonly invocationFunction; private readonly maxQueueLength; private readonly invocationQueue; /** * @param lock The lock to used for synchronization. * @param invocationFunction The function to invoke. * @param maxQueueLength The maximum length of the queue. */ constructor(lock: SpinWaitLock, invocationFunction: (args: Targs) => Promise<Treturn>, maxQueueLength?: number); /** * Invokes the function with the given arguments, if an execution is already underway en-ques the current invocation. * @param args The arguments to pass to the invocationFunction. * @param spinTime The time to wait between attempts to acquire the lock. * @param index The index to replace in the queue, if an execution is already active. * @returns A promise that resolves to the result of the invocation. */ invoke(args: Targs, spinTime?: number, index?: number | undefined): Promise<InvocationResult<Treturn>>; /** * Deletes the invocation at the given index. * @param index The index of the invocation to delete. * @returns void */ delete(index: number): void; /** * Returns an iterator for the invocation queue. * @returns An iterator for the invocation queue. * @example * ```typescript * const invocationQueue = new SequentialInvocationQueue<number[], void>(new SpinWaitLock(), sensitiveWork); * invocationQueue.invoke([undefined, 0]); * invocationQueue.invoke([undefined, 1]); * invocationQueue.invoke([undefined, 2]); * for (const invocation of invocationQueue) { * console.log(invocation); * } * ``` */ [Symbol.iterator](): IterableIterator<Targs>; /** * Clears the invocation queue. * @returns void */ clear(): void; [Symbol.asyncDispose](): void; }