控制最大并发数

JavaScript

class PromisePool {

  constructor(max, fn) {

    this.max = max; // 最大并发数

    this.fn = fn;   // 自定义的请求函数

    this.pool = []; // 并发池

    this.urls = []; // 剩余的请求地址

  }

  start(urls) {

    this.urls = urls;

    // 先循环把并发池塞满

    while (this.pool.length < this.max) {

      let url = this.urls.shift();

      this.setTask(url);

    }

    // 利用Promise.race 方法来获得并发池中某任务完成的信号

    let race = Promise.race(this.pool);

    return this.run(race);

  }

  run(race) {

    race

      .then(res => {

        // 每当并发池跑完一个任务,就再塞入一个任务

        let url = this.urls.shift();

        this.setTask(url);

        return this.run(Promise.race(this.pool));

      });

  }

  setTask(url) {

    if (!url) return;

    let task = this.fn(url);

    this.pool.push(task); // 将该任务推入pool并发池中

    console.log(`\x1B[43m ${url} 开始,当前并发数:${this.pool.length}`);

    task.then(res => {

      // 请求结束后将该Promise任务从并发池中移除

      this.pool.splice(this.pool.indexOf(task), 1);

      console.log(`\x1B[43m ${url} 结束,当前并发数:${this.pool.length}`);

    });

  }

}

// test

const URLs = [

  'bytedance.com',

  'tencent.com',

  'alibaba.com',

  'microsoft.com',

  'apple.com',

  'hulu.com',

  'amazon.com'

];

let dur = 0;

// 自定义请求函数

let requestFn = url => {

  return new Promise(resolve => {

    setTimeout(_ => {

      resolve(`任务 ${url} 完成`);

    }, 1000 * dur++)

  }).then(res => {

    console.log('外部逻辑 ', res);

  })

}

const pool = new PromisePool(3, requestFn); // 并发数为3

pool.start(URLs);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值