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('错了'))
};
img.src = url;
})
}
function limitLoad(urls, handler, limit) {
let sequence = [].concat(urls);
let promises = sequence.splice(0, limit).map((url, index) => {
return handler(url).then(() => {
return index;
})
});
return sequence
.reduece((pCollect, url, currentIndex) => {
return pCollect
.then(() => {
return promises.race(promises);
})
.then(fastedIndex => {
promises[fastedIndex] = handler(url).then(() => {
return fastedIndex;
})
})
.catch(err => {
console.error(err);
});
}, Promise.resolve())
.then(() => {
return Promise.all(promises);
});
}
limitLoad(urls, loadImg, 3)
.then(res => {
console.log('加载完毕');
console.log(res);
})
.catch(err => {
console.error(err);
})
console