promise to achieve perform image (tandem operation) in accordance with the specified order to load

promise to achieve load pictures executed in the order specified, to load the second, then loaded the first, third and finally loaded

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>promise</title>
</head>
<body>

</body>
<script>
    function loadImg(src) {
        var promise = new Promise(function (resolve, reject) {
            var img = document.createElement('img');
            img.onload =function () {
                resolve(img)
            }
            img.onerror =function () {
                reject()
            }
            img.src =src
        })

        return promise;
    }
    
// Promise implement to load the second picture, and then load the first picture, the last third load pictures

    var src1='https://img.mukewang.com/5dccac000001839c18720764.jpg';  //1872 764
    var result1 = loadImg(src1);

    var src2 ='https://img3.mukewang.com/szimg/5dbffa9109ef425a12000676-360-202.png'; //360 202
    var result2 =loadImg(src2);

    var src3 ='https://www.imooc.com/static/img/index/logo.png'; //200 80
    var result3 =loadImg(src3);

    result2.then(function (img) {
        the console.log ( ' the second image is loaded ' , img.width, img.height)
         return RESULT1
    }).then(function (img) {

        console.log ( ' the first image is loaded ' , img.width, img.height)
         return result3
    }).then(function (img) {

        the console.log ( ' the third image is loaded ' , img.width, img.height)
         // return result2 
    }). the catch ( function (EX) {
        console.log(ex)
        
    })
</script>
</html>

 The order of execution results

Guess you like

Origin www.cnblogs.com/malong1992/p/11967092.html