export interface ITask { (): T; } export interface IDisposable { dispose(): void; } export declare function raceTimeout(promise: Promise, timeout: number, onTimeout?: () => T | undefined): Promise; /** * * 以节流方式执行 async 回调任务 * A helper to prevent accumulation of sequential async tasks. * * Imagine a mail man with the sole task of delivering letters. As soon as * a letter submitted for delivery, he drives to the destination, delivers it * and returns to his base. Imagine that during the trip, N more letters were submitted. * When the mail man returns, he picks those N letters and delivers them all in a * single trip. Even though N+1 submissions occurred, only 2 deliveries were made. * * The throttler implements this via the queue() method, by providing it a task * factory. Following the example: * ```ts * const throttler = new Throttler(); * const letters = []; * * function deliver() { * const lettersToDeliver = letters; * letters = []; * return makeTheTrip(lettersToDeliver); * } * * function onLetterReceived(l) { * letters.push(l); * throttler.queue(deliver); * } * ``` */ export declare class Throttler { private activePromise; private queuedPromise; private queuedPromiseFactory; constructor(); queue(promiseFactory: ITask>): Promise; } /** * 顺序的执行 async 回调任务 * * @example * ```ts * const sleep = (time, val) => new Promise(rs => setTimeout(() => rs(val), time)); * const seq = new Sequencer(); * let i = 0; * for(let b =0; b < 100; b++) seq.queue(() => sleep(100, ++i).then(d => console.log(d))); * ``` */ export declare class Sequencer { private current; queue(promiseTask: ITask>): Promise; } export declare class SequencerByKey { private promiseMap; queue(key: TKey, promiseTask: ITask>): Promise; } export interface IScheduledLater extends IDisposable { isTriggered(): boolean; } /** Can be passed into the Delayed to defer using a microtask */ export declare const MicrotaskDelay: unique symbol; /** * Returns an error that signals cancellation. */ export declare function canceled(): Error; /** * 防抖式的执行任务 * * A helper to delay (debounce) execution of a task that is being requested often. * * Following the throttler, now imagine the mail man wants to optimize the number of * trips proactively. The trip itself can be long, so he decides not to make the trip * as soon as a letter is submitted. Instead he waits a while, in case more * letters are submitted. After said waiting period, if no letters were submitted, he * decides to make the trip. Imagine that N more letters were submitted after the first * one, all within a short period of time between each other. Even though N+1 * submissions occurred, only 1 delivery was made. * * The delayer offers this behavior via the trigger() method, into which both the task * to be executed and the waiting period (delay) must be passed in as arguments. Following * the example: * ```ts * const delayer = new Delayer(WAITING_PERIOD); * const letters = []; * * function letterReceived(l) { * letters.push(l); * delayer.trigger(() => { return makeTheTrip(); }); * } * ``` */ export declare class Delayer implements IDisposable { defaultDelay: number | typeof MicrotaskDelay; private deferred; private completionPromise; private doResolve; private doReject; private task; constructor(defaultDelay: number | typeof MicrotaskDelay); trigger(task: ITask>, delay?: number | typeof MicrotaskDelay): Promise; isTriggered(): boolean; cancel(): void; private cancelTimeout; dispose(): void; } /** * A helper to delay execution of a task that is being requested often, while * preventing accumulation of consecutive executions, while the task runs. * * The mail man is clever and waits for a certain amount of time, before going * out to deliver letters. While the mail man is going out, more letters arrive * and can only be delivered once he is back. Once he is back the mail man will * do one more trip to deliver the letters that have accumulated while he was out. */ export declare class ThrottledDelayer { private delayer; private throttler; constructor(defaultDelay: number); trigger(promiseFactory: ITask>, delay?: number): Promise; isTriggered(): boolean; cancel(): void; dispose(): void; } /** * 创建一个初始状态为关闭、最后为永久打开的一个屏障 * A barrier that is initially closed and then becomes opened permanently. */ export declare class Barrier { private _isOpen; private _promise; private _completePromise; constructor(); isOpen(): boolean; open(): void; wait(): Promise; } /** * A barrier that is initially closed and then becomes opened permanently after a certain period of * time or when open is called explicitly */ export declare class AutoOpenBarrier extends Barrier { private readonly _timeout; constructor(autoOpenTimeMs: number); open(): void; } export declare const sleep: (milliseconds?: number, value?: T | (() => T | Promise)) => Promise; /** * 随机等待一定范围的时间(单位为毫秒) * @param min 等待最小时间 * @param max 等待最大时间 * @returns 返回实际等待的时间 */ export declare function wait(min?: number, max?: number): Promise; export declare function retry(task: ITask | T>, delay: number, retries: number, validator?: (r: T, index: number) => boolean): Promise; /** * 并发执行多任务 * @eample * ```ts * async function concurrencyTest(paralelism = 5, total = 100) { * const startTime = Date.now(); * const taskList = Array.from({ length: total }) * .fill(1) * .map((_v, idx) => () => sleep(50, idx)); * * console.log(tasklist); * const result = await concurrency(taskList, paralelism); * console.log('TimeCost:', Date.now() - startTime); * * return result; * } * * await concurrencyTest(10); * await concurrencyTest(100); * ``` */ export declare function concurrency(taskList: ITask>[], maxDegreeOfParalellism?: number): Promise<{ index: number; result: T; error: E; }[]>; export interface ILimitedTaskFactory { factory: ITask>; c: (value: T | Promise) => void; e: (error?: unknown) => void; } /** * A helper to queue N promises and run them all with a max degree of parallelism. The helper * ensures that at any time no more than M promises are running at the same time. */ export declare class Limiter { private _size; private runningPromises; private maxDegreeOfParalellism; private outstandingPromises; private onFinishCallbackFns; constructor(maxDegreeOfParalellism: number); onFinished(callback: (...args: unknown[]) => unknown): void; get size(): number; queue(factory: ITask>): Promise; private consume; private consumed; dispose(): void; } export declare function getPromiseState(p: Promise): Promise;