用 JS写一个pool-2 换种思路

25 阅读1分钟

这里我们写了一个 pool,

  • 这里的思路是直接给 promise 再加一个 then,注册从执行成功后删除pool里面对应的任务。 然后通过 Promise.race来等待 pool 中的一个执行完成

我们可以换一种思路,当发现 pool 满了之后,我们直接new一个 Promise,在pool 里面任意一个执行完成之后,执行这个 Promise 的 resolve,从而进行接下来的程序。

  • 在这里我们同样要给当前的 task 注册一个 then 处理函数,只不过不是从 Pool 里面删除对应的任务,而是获取“堵塞”Promise 的 resolve,并且执行。

具体代码如下

class Pool {
  constructor(concurrency) {
    this.concurrency = concurrency;
    this.count = 0;
    this.queue = [];
  }
  async add(task) {
    if (this.count == this.concurrency) {
      await new Promise((res) => this.queue.push(res));
    }
    this.count++;
    const taskPromise = Promise.resolve(task());
    taskPromise.then(() => {
      if (this.queue.length) {
        this.queue.shift()(); 
      }
    });
  }
}