使用Promise对象判断图片是否加载完成

直接上代码

 loadimage(url){
            return  new Promise((resolve, reject) =>{
                let aimg = new Image()
                aimg.src = url
                aimg.onload = ()=>{
                    let are = aimg.naturalWidth*aimg.naturalHeight
                    resolve(are)
                }
                aimg.onerror = ()=>{
                    reject(url)
                }
            });
        }

多张图片

loadimages(images){
              let promiseAll = [], imgs = [], total = images.length;
              for (let i = 0; i < total; i++) {
                promiseAll[i] = new Promise((resolve, reject) => {
                    imgs[i] = new Image();
                    imgs[i].src = images[i];
                    imgs[i].onload =()=> {
                        resolve(imgs[i]);
                    };
                    imgs[i].onerror =()=>{
                        reject('false')
                        }
                })
              }
              Promise.all(promiseAll).then(img => {
                // 全部图片加载完成
              })
        }

你可能感兴趣的:(js,es6)