图片并行加载示例 -- Promise

function loadImg(src){
    return new Promise( (resolve, reject) => {
         let img = document.createElement('img');
         img.src = src;
         img.onload = function() {
             resolve(img);
         }
         img.onerror = function(err){
             reject(err)
         }
    })
}
function showImgs(imgs) {
    imgs.forEach(function(img){
         document.body.appendChild(img);
    })
}
Promise.all([
    loadImg('1.jpg'),
    loadImg('2.jpg'),
    loadImg('3.jpg'),
    loadImg('4.jpg')
]).then(showImgs);

你可能感兴趣的:(图片并行加载示例 -- Promise)