限制并发数量的异步任务执行器

58 阅读1分钟
class AsyncExecutor {

  constructor(limit) {

    this.limit = limit;

    this.runningCount = 0;

    this.taskQueue = [];

  }

  executeAsyncTask(task) {

    return new Promise((resolve, reject) => {

      const execute = async () => {

        try {

          resolve(await task());

        } catch (err) {

          reject(err)

        } finally {

          this.runningCount--;

          this.runNextTask();

        }

      }

      if (this.runningCount < this.limit) {

        this.runningCount++;

        execute();

      } else {

        this.taskQueue.push(execute);

      }

    })

  }

  runNextTask() {

    if (this.runningCount < this.limit && this.taskQueue.length) {

      this.runningCount++;

      const execute = this.taskQueue.shift();

      execute();

    }

  }

  async executeAsyncTasks(tasks) {

    const result = [];

    for (const task of tasks) {

      result.push(this.executeAsyncTask(task));

    }

    return result

  }
}