Promise.all():
1 <body> 2 <div id="pic" ></div> 3 <script> 4 const imgs = [ 5 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588606301799&di=26e46595e4a886700fb38dd008909934&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201710%2F07%2F20171007134945_84Cnd.jpeg', 6 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1426668281,3085506529&fm=26&gp=0.jpg', 7 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588606301800&di=28eb474abf2022fb1f4f7e1525882fa3&imgtype=0&src=http%3A%2F%2Fgss0.baidu.com%2F7LsWdDW5_xN3otqbppnN2DJv%2Fzhidao%2Fpic%2Fitem%2Fdcc451da81cb39db719c5aa3db160924aa1830e2.jpg' 8 ]; 9 10 11 function loadImagePro(picUrl) { 12 return new Promise(function (resolve, reject) { 13 const img = new Image(); 14 img.onload = () => void resolve(img); // 将标签元素传入resolve15 img.src = picUrl;16 // img.onerror = reject('加载失败'); 17 }); 18 } 19 /* 20 // 返回一个Promise实例组成的数组 21 const promiseArr = imgs.map(picUrl => loadImagePro(picUrl)); 22 23 Promise.all(promiseArr) 24 .then(function (picArr) { 25 console.log(picArr); // 返回所有标签元素组成的数组 26 picArr.forEach(function (item) { 27 console.log(item); 28 document.getElementById('pic').appendChild(item); 29 }); 30 }); 31 */ 32 33 // ES6 写法 34 Promise.all(imgs.map(picUrl => loadImagePro(picUrl))) 35 .then(picArr => { 36 picArr.forEach(item => document.getElementById('pic').appendChild(item)); 37 }); 38 console.log('末尾'); 39 </script> 40 </body>
Promise.race():
1 <body> 2 <div id="pic" ></div> 3 <script> 4 const imgs = [ 5 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588606301799&di=26e46595e4a886700fb38dd008909934&imgtype=0&src=http%3A%2F%2Fb-ssl.duitang.com%2Fuploads%2Fitem%2F201710%2F07%2F20171007134945_84Cnd.jpeg', 6 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1426668281,3085506529&fm=26&gp=0.jpg', 7 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1588606301800&di=28eb474abf2022fb1f4f7e1525882fa3&imgtype=0&src=http%3A%2F%2Fgss0.baidu.com%2F7LsWdDW5_xN3otqbppnN2DJv%2Fzhidao%2Fpic%2Fitem%2Fdcc451da81cb39db719c5aa3db160924aa1830e2.jpg' 8 ]; 9 10 11 function loadImagePro(picUrl) { 12 return new Promise(function (resolve, reject) { 13 const img = new Image(); 14 img.onload = () => void resolve(img); // 将标签元素传入resolve15 img.src = picUrl;16 // img.onerror = reject('加载失败'); 17 }); 18 } 19 20 // 返回一个Promise实例组成的数组 21 const promiseArr = imgs.map(picUrl => loadImagePro(picUrl)); 22 23 // 只接收promiseArr数组中,最先返回的promise实列,然后执行这个实例的.then() 24 // Promise.race(promiseArr).then(function (item) {// 接收到Promise.race返回的标签元素 25 // document.getElementById('pic').appendChild(item); 26 // }); 27 28 // ES6 写法 29 Promise.race(imgs.map(picUrl => loadImagePro(picUrl))).then(item => document.getElementById('pic').appendChild(item)); 30 31 console.log('末尾'); 32 </script>