第一条是否等价于第二条呢
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="" alt="" id="img">
<script>
/*
实现一个图片的加载;设置第一张图片加载1s之后加载第二张图片,可参考如下效果图:
http://img1.sycdn.imooc.com/climg//5b16558d00011ed506000338.jpg
http://img1.sycdn.imooc.com/climg//5b165603000146ca06000338.jpg
http://img1.sycdn.imooc.com/climg//5b1656140001c89906000338.jpg
第一步:设置一个函数,把图片的url地址作为参数
第二步:实例化promise对象
第三步:建立图像对象;设置图片的地址;把图片节点插入到body中
第四步:图片加载完成后执行resolve
*/
const urlImgPromise = (url) => {
return new Promise((resolve, reject) => {
const img = new Image();
//当图片加载完成
img.onload = () => {
setTimeout(() => {
document.body.appendChild(img);
resolve();
}, 1000);
}
img.onerror = () => {
reject(new Error(`Could not load image at${url}`));
}
img.src = url;
});
};
// const imgDOM = document.getElementById('img');
// var imgnew = document.createElement('img');
// var imgtwo = document.createElement('img');
// document.body.appendChild(imgnew);
// document.body.appendChild(imgtwo);
urlImgPromise('http://img1.sycdn.imooc.com/climg//5b16558d00011ed506000338.jpg').then(() => {
// setTimeout(() => {
// imgDOM.src = img.src;
// }, 1000)
// return urlImgPromise('http://img1.sycdn.imooc.com/climg//5b165603000146ca06000338.jpg'); //等价于
return new Promise((resolve, reject) => {
resolve(urlImgPromise('http://img1.sycdn.imooc.com/climg//5b165603000146ca06000338.jpg'));
})
}).catch(err => {
console.log(err);
}).then(() => {
return urlImgPromise('http://img1.sycdn.imooc.com/climg//5b1656140001c89906000338.jpg');
}).catch(err => {
console.log(err);
})
</script>
</body>
</html>
相关截图:
21
收起
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星