[Javascript] Paralle Task

function timeout(time) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
}

class ParalleTask {
  constructor(paralleCount = 2) {
    this.tasks = [];
    this.paralleCount = paralleCount;
    this.runningCount = 0;
  }

  add(task) {
    return new Promise((resolve, reject) => {
      this.tasks.push({ task, resolve, reject });
      this._run();
    });
  }

  _run() {
    while (this.runningCount < this.paralleCount && this.tasks.length) {
      this.runningCount++;
      const { task, resolve, reject } = this.tasks.shift();
      task()
        .then(resolve)
        .catch(reject)
        .finally(() => {
          this.runningCount--;
          this._run();
        });
    }
  }
}

const superTask = new ParalleTask();

function addTask(time, name) {
  superTask
    .add(() => timeout(time))
    .then(() => {
      console.log(`${name} is done`);
    });
}

addTask(10000, "Task 1");
addTask(5000, "Task 2");
addTask(3000, "Task 3");
addTask(4000, "Task 4");
addTask(5000, "Task 5");

// after 5 second, finish Task 2
// then after 3 second, finish Task 3
// then after 2 second, finish Task 1
// then after 2 second, finish Task 4
// then after 3 second, finish Task 5
// Total 15 seconds

 

posted @   Zhentiw  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2022-09-03 [Typescript] 14. Easy - Parameters
2022-09-03 [Typescript] 13. Easy - Unshift
2022-09-03 [Typescript] 12. Easy - Push
2022-09-03 [Typescript] 11. Medium - Equal
2021-09-03 [Cloud Architect] 4. Introduction to Design for Cost, Performance, & Scalability
2019-09-03 [Dart] Capture and Handle Data Sequences with Streams in Dart
2019-09-03 [Javascript] Run asynchronous functions in sequence using reduce
点击右上角即可分享
微信分享提示