欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Promise图片的异步加载(练习)

程序员文章站 2024-02-14 17:19:10
...

我们来实现一个图片的加载;设置第一张图片加载1s之后加载第二张图片:

<!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>Promise的应用-异步加载</title>
    <style>
      img{
          width: 300px;
          padding: 10px;
      }
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        const loadImgAsync = (url)=> {
            return new Promise((resolve,reject) =>{
                const img = new Image();
                img.onload = () => {
                    setInterval(() => {
                        
                        resolve(img);
                    }, 1000);
                }
                img.onerror = () => {
                    reject(new Error(`Could not load the image at ${url}`));
                }
                img.src = url;
            })
        }
        const box = document.getElementById('box');
        loadImgAsync("http://img1.sycdn.imooc.com\/climg/5b16558d00011ed506000338.jpg")
        .then((img)=>{
            box.appendChild(img);
            return loadImgAsync("http://img1.sycdn.imooc.com\/climg/5b165603000146ca06000338.jpg ");
        }).then((img)=>{
            box.appendChild(img);
            return loadImgAsync("http://img1.sycdn.imooc.com\/climg/5b1656140001c89906000338.jpg ")
        }).then((img)=>{
            box.appendChild(img);
        })

    </script>
</body>
</html>

以上是我学习过程中自己写的练习题,

结合Promise解决回调地狱,并实现图片的异步加载。

相关标签: #ES6之Promise