promise实现图片按照指定的加载顺序执行(串联操作)
promise实现图片按照指定的加载顺序执行,先加载第二张,再加载第一张,最后加载第三张
<!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实现先加载第二张图片,再加载第一张图片,最后加载第三张图片 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) { console.log('第二个图片加载完成',img.width,img.height) return result1 }).then(function (img) { console.log('第一个图片加载完成',img.width,img.height) return result3 }).then(function (img) { console.log('第三个图片加载完成',img.width,img.height) // return result2 }).catch(function (ex) { console.log(ex) }) </script> </html>
执行顺序结果