promise實現圖片按照指定的加載順序執行,先加載第二張,再加載第一張,最後加載第三張html
<!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>
執行順序結果promise