基于async/await/iterator实现的异步请求池

基于async/await/iterator实现的异步请求池_第1张图片

用法

//导入
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

你可能感兴趣的:(javascript,前端,异步编程)