{
function loadImg(src) {
return new Promise(function (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(img => {
document.body.appendChild(img)
});
}
Promise.all([
loadImg('http://pic37.nipic.com/20140113/8800276_184927469000_2.png'),
loadImg('http://pic37.nipic.com/20140113/8800276_184927469000_2.png'),
loadImg('http://pic37.nipic.com/20140113/8800276_184927469000_2.png')
]).then(showImgs)
}
多个图片服务器, 加载最快的一个
{
function loadImg(src) {
return new Promise((resolve, reject) => {
let img = document.createElement('img')
img.src = src
img.onload = function () {
resolve(img)
}
img.onerror = function () {
reject(err)
}
})
}
function showImg(img){
document.body.appendChild(img)
}
Promise.race([
loadImg('http://img2.imgtn.bdimg.com/it/u=234634259,4236876085&fm=26&gp=0.jpg'),
loadImg('http://img4.imgtn.bdimg.com/it/u=2153937626,1074119156&fm=26&gp=0.jpg'),
loadImg('http://img1.imgtn.bdimg.com/it/u=1483033257,4287748004&fm=26&gp=0.jpg')
]).then(showImg)
}