Open haizhilin2013 opened 3 months ago
function loadImage(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.src = url;
img.onload = () => resolve(url);
img.onerror = () => reject(new Error(`Failed to load image at ${url}`));
});
}
function loadImages(urls, maxConcurrent) {
let index = 0; // 当前图片索引
const results = []; // 存储加载结果
const loading = []; // 存储正在加载的Promise
return new Promise((resolve, reject) => {
function next() {
if (index >= urls.length && loading.length === 0) {
// 所有图片都加载完毕
resolve(results);
return;
}
while (loading.length < maxConcurrent && index < urls.length) {
const url = urls[index++];
const promise = loadImage(url)
.then(result => {
results.push(result);
loading.splice(loading.indexOf(promise), 1);
next();
})
.catch(error => {
loading.splice(loading.indexOf(promise), 1);
reject(error);
});
loading.push(promise);
}
}
next();
});
第1938天 使用promise实现,加载100张图片,每次最多同时加载5张图片
3+1官网
我也要出题