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));
}