UNPKG

@ayonli/jsext

Version:

A JavaScript extension package for building strong and modern applications.

48 lines (47 loc) 1.32 kB
/** * This module provides a mechanism to handle tasks sequentially and prevent * concurrency conflicts. * @module */ export declare class Queue<T> { private channel?; private errorHandler?; constructor(handler: (data: T) => Promise<void>, bufferSize?: number); push(data: T): Promise<void>; close(): void; onError(handler: (err: unknown) => void): void; [Symbol.dispose](): void; } /** * Processes data sequentially by the given `handler` function and prevents * concurrency conflicts, it returns a {@link Queue} instance that we can push * data into. * * @param bufferSize The maximum capacity of the underlying channel, once * reached, the push operation will block until there is new space available. * By default, this option is not set and use a non-buffered channel instead. * * @example * ```ts * import queue from "@ayonli/jsext/queue"; * * const list: string[] = []; * const q = queue(async (str: string) => { * await Promise.resolve(null); * list.push(str); * }); * * q.onError(err => { * console.error(err); * }) * * await q.push("foo"); * await q.push("foo"); * * console.log(list.length); * q.close(); * // output: * // 2 * ``` */ export default function queue<T>(handler: (data: T) => Promise<void>, bufferSize?: number): Queue<T>;