限制异步操作的并发个数

    var urls = [

      "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting1.png",

      "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting2.png",

      "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting3.png",

      "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting4.png",

      "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/AboutMe-painting5.png",

      "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn6.png",

      "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn7.png",

      "https://hexo-blog-1256114407.cos.ap-shenzhen-fsi.myqcloud.com/bpmn8.png",

    ];

    function loadImg(url) {

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

        const img = new Image();

        img.onload = function() {

          console.log("一张图片加载完成");

          resolve(img);

        };

        img.onerror = function() {

          reject(new Error('Could not load image at' + url));

        };

        img.src = url;

      });

    }

   es7

    async function limitFn(limit,arr,fn) {

      let res = [];

      let cur = [];

      for (let i = 0; i < arr.length; i++) {

        let p = Promise.resolve().then(() => fn(arr[i]));

        res.push(p);

        if (limit < arr.length) {

          let e = p.finally(() => cur.slice(cur.indexOf(e),1));

          cur.push(e);

          if (cur.length>limit) {

            await Promise.race(cur);

          }

        }

      }

      return Promise.all(res);

    }

es6

    function limitFn1(limit,arr,fn) {

      let counter = 0;//索引计数

      let res = []; //返回结果列

      let cur = [];//当先加载列

      function enqueue() {

        if (counter === arr.length) return Promise.resolve(); // 最后返回promise

        let p = Promise.resolve().then(() => fn(arr[counter++]));

        res.push(p);

        let r = Promise.resolve();//提升作用域

        if (limit < arr.length) {

          let e = p.finally(() => cur.slice(cur.indexOf(e),1));//添加回调删除已经加载完的

          cur.push(e);

          if (cur.length >= limit) {

            r = Promise.race(cur);//大于并发就等一个先完成

          }

        }

        return r.then(() => enqueue()); // 返回必须是promise,回调继续加载

      }

      return enqueue().then(() => Promise.all(res));

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值