fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[js] 第1938天 使用promise实现,加载100张图片,每次最多同时加载5张图片

Open haizhilin2013 opened this issue 1 year ago • 1 comments

第1938天 使用promise实现,加载100张图片,每次最多同时加载5张图片

3+1官网

我也要出题

haizhilin2013 avatar Aug 04 '24 20:08 haizhilin2013

步骤1:创建加载单张图片的函数:该函数loadImage接收一个图片的URL,返回一个Promise,当图片加载成功时,调用resolve方法,否则调用reject方法。

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

步骤2:创建一个函数来管理加载的图片

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

Liu-code3 avatar Aug 06 '24 14:08 Liu-code3