乐趣区

关于javascript:基于asyncawaititerator实现的异步请求池

用法

// 导入
import asyncPool from "../lib/index";
/* 参数
 myIterator
    要并发解决的可迭代对象
 handler
    function 异步处理函数, 返回 promise,
 workers
    Number 并发数
 返回值
    Array limit 个 promise 数组
*/
asyncPool(myIterator,handler,workers);

应用场景

1、页面内含大量图片时限度并发 HTTP 连接数

let imgs = ['https://www.yuanzhua.cn/img_for_demo/pic_001.jpg','https://www.yuanzhua.cn/img_for_demo/pic_002.jpg', 'https://www.yuanzhua.cn/img_for_demo/pic_003.jpg','https://www.yuanzhua.cn/img_for_demo/pic_004.jpg','https://www.yuanzhua.cn/img_for_demo/pic_005.jpg','https://www.yuanzhua.cn/img_for_demo/pic_006.jpg', 'https://www.yuanzhua.cn/img_for_demo/pic_007.jpg','https://www.yuanzhua.cn/img_for_demo/pic_008.png', 'https://www.yuanzhua.cn/img_for_demo/pic_009.jpg', 'https://www.yuanzhua.cn/img_for_demo/pic_010.jpg', 'https://www.yuanzhua.cn/img_for_demo/pic_011.png', 'https://www.yuanzhua.cn/img_for_demo/pic_012.jpg', 'https://www.yuanzhua.cn/img_for_demo/pic_013.jpg', 'https://www.yuanzhua.cn/img_for_demo/pic_014.jpg','https://www.yuanzhua.cn/img_for_demo/pic_015.jpg'];

function loadImg(url){return new Promise((resolve, reject)=>{let img=new Image();
                img.src=url;
                img.style.width=
                img.onload=function () {
                    this.width=200;
                    // this.
                    document.body.append(this);
                    resolve()}
                img.onerror=function () {reject()
                }
            });
}

Promise.all(asyncPool(imgs.values(),loadImg,5)).then(() => console.log('done'))

Github 开源地址 https://github.com/yuanzhuacn/asyncPool

退出移动版