JSFiddle - React, Tailwind, and code Playground
by ruirui
HTML
<div id="image-list">
</div>
CSS
img {
display: block;
margin-top: 10px;
}
JavaScript
function loadImg(url) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = function() {
resolve(img)
};
img.onerror = function(e) {
reject(e)
};
img.src = url;
})
}
function addToHtml(img) {
var imageList = document.getElementById('image-list');
imageList.appendChild(img);
}
var urls = ['http://season.jpanj.com/001.jpg', 'http://season.jpanj.com/002.jpg', 'http://season.jpanj.com/003.jpg', 'http://season.jpanj.com/004.jpg', 'http://season.jpanj.com/005.jpg', 'http://season.jpanj.com/006.jpg', 'http://season.jpanj.com/007.jpg', 'http://season.jpanj.com/008.jpg', 'http://season.jpanj.com/009.jpg', 'http://season.jpanj.com/010.jpg', 'http://season.jpanj.com/011.jpg'];
const loadImages = urls.map(loadImg);
function imgQueue(things) {
let promise = Promise.resolve();
return things.reduce((promise,thing,index)=>{
return promise.then(()=>{
console.log('处理第'+index+'个图片');
return loadImages[index];
}).then((img)=>{
console.log('第'+index+'个图片加载完成');
addToHtml(img)
}).catch(()=>{
console.log('error');
})
},Promise.resolve())
return promise;
}
imgQueue(loadImages).then(()=>{console.log('finish all')});