util-helpers
Version:
71 lines (70 loc) • 1.68 kB
TypeScript
type AsyncFunc<T = any> = () => Promise<T>;
/**
* 并发控制器
*
* @class
* @param {number} [maxConcurrency=2] 最大并发数量。默认 `2`。
* @example
* // 最多同时运行 3 个异步任务
* const controller = new ConcurrencyController(3);
*
* const urls = ['/api/1', '/api/2', '/api/3', '/api/4', '/api/5', '/api/6'];
* const results = await Promise.all(urls.map(url => controller.add(() => fetch(url))));
*
* // 获取状态
* controller.getStatus();
*
* // 暂停队列
* controller.pause();
*
* // 恢复队列
* controller.resume();
*
* // 设置最大并发数量,并立即运行队列中的任务。
* controller.setMaxConcurrency(4);
*
*/
declare class ConcurrencyController {
private maxConcurrency;
private runningCount;
private queue;
private isPaused;
constructor(maxConcurrency?: number);
/**
* 加入队列
*
* @param {Function} task 异步任务函数。
* @returns 任务的 Promise 对象。
*/
add<T>(task: AsyncFunc<T>): Promise<T>;
/**
* 运行队列中的任务
*
* @private
*/
private _run;
/**
* 获取状态
*/
getStatus(): {
running: number;
waiting: number;
maxConcurrency: number;
paused: boolean;
};
/**
* 设置最大并发数量,并立即运行队列中的任务。
*
* @param {number} maxConcurrency 最大并发数量。不能小于 `1`。
*/
setMaxConcurrency(maxConcurrency: number): void;
/**
* 暂停队列
*/
pause(): void;
/**
* 恢复队列
*/
resume(): void;
}
export default ConcurrencyController;