Promise练习

2023-09-28 22:22:11 浏览数 (1)

需求

一次加载一张图片添加到 body 中,前面图片加载失败后面图片不加载:

代码语言:html复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promise练习</title>
</head>
<body>
<script>
    const arr = [
        "https://img.yuanmabao.com/zijie/pic/2023/09/28/ikkq25aaima.jpg",
        "https://img.yuanmabao.com/zijie/pic/2023/09/28/ikkq25aaima.jpg",
        "https://img.yuanmabao.com/zijie/pic/2023/09/28/ikkq25aaima.jpg",
    ];

    const loadImage = (url) => {
        return new Promise((resolve, reject) => {
            let oImg = new Image();
            oImg.src = url;
            oImg.onload = function () {
                resolve(oImg);
            }
            oImg.onerror = function () {
                reject("图片加载失败");
            }
        });
    }

    /*
    简化之前的代码
    let p2 = loadImage(arr[0]).then(function (oImg) {
        // console.log(oImg);
        console.log("1");
        document.body.appendChild(oImg);
        return loadImage(arr[1]);
    }, function (msg) {
        console.log(msg);
    });
    let p3 = p2.then(function (oImg) {
        console.log("2");
        // console.log(oImg);
        document.body.appendChild(oImg);
        return loadImage(arr[2]);
    }, function (msg) {
        console.log(msg);
    });
    p3.then(function (oImg) {
        console.log("3");
        // console.log(oImg);
        document.body.appendChild(oImg);
    }, function (msg) {
        console.log(msg);
    });
    */

    // 简化之后的代码
    loadImage(arr[0]).then(function (oImg) {
        // console.log(oImg);
        console.log("1");
        document.body.appendChild(oImg);
        return loadImage(arr[1]);
    }).then(function (oImg) {
        console.log("2");
        // console.log(oImg);
        document.body.appendChild(oImg);
        return loadImage(arr[2]);
    }).then(function (oImg) {
        console.log("3");
        // console.log(oImg);
        document.body.appendChild(oImg);
    }).catch(function (msg) {
        console.log(msg);
    });
</script>
</body>
</html>

我正在参与2023腾讯技术创作特训营第二期有奖征文,瓜分万元奖池和键盘手表

0 人点赞