UNPKG

wg-little-tools

Version:

常用工具类

34 lines (30 loc) 808 B
/** * @description 并发任务 */ export class SuperTask { constructor(parallelCount = 2) { this.parallelCount = parallelCount; // 最大并发数 this.runningCount = 0; // 正在运行的任务数 this.taskList = []; // 任务集合 } add(task) { return new Promise((resolve, reject) => { this.taskList.push({ task, resolve, reject }); this.run(); }) } run() { if (this.taskList.length && this.runningCount < this.parallelCount) { const { task, resolve, reject } = this.taskList.shift(); // 先进先出 this.runningCount++; task().then(resolve, reject).finally(() => { this.runningCount--; this.run(); }) } } }