ES6——異步操作之Promise
阿新 • • 發佈:2018-08-05
實例 image 基本 for 概念 return app === new
基本概念:
Promise : 是 ES6 中新增的異步編程解決方案,提現在代碼中他是一個對象 可以通過Promise構造函數來實例化。
-new Promise(cb) ===> 實例的基本使用,Pending Resolved Rejected
> 兩個原型方法:
-Promise.prototype.then() -Promise.prototype.catch()
> 兩個常用的 靜態方法。
-Promise.all();
-Promise.resolve();
conse imgs=[ "http://i1.piimg.com/1949/4f411ed22ce88950.jpg","http://i1.piimg.com/1949/5a35e8c2b246ba6f.jpg", "http://i1.piimg.com/1949/1afc870a86dfec5f.jpg" ];
//new Promise(cb); //Pending(進行中)===>Resolved(已完成) //Pending(進行中)===>Rejected(已失效) const p = new Promise(function(resolve,reject){ const img = new Image(); img.onload=function(){ resolve(this); }; img.onerror=function(err){ reject(new Error("圖片加載失敗")); }; }) console.log(123); p.then(function(img){ console.log("加載完成"); document.body.appendChild(img); }).catch(function(err){ console.log(err); }); console.log(456);
//////////////封裝函數
function loadImg(url){ const p = new Promise(function(resolve,reject){ const img= new Image(); img.onload=function(){ resolve(this); }; img.onerror=function(err){ reject(new Error("圖片加載失敗")); }; }); return p; } loadImg(imgs[0]).then(function(img){ document.body.appendChild(img); })
///////Promise.all() 可將多個 Promise實例包裝成一個新的Promise實例。
const allDone=Promise.all([loadImg(imgs[0]),loadImg(imgs[1]),loadImg(imgs[2]),loadImg(imgs[""])]); allDone.then(function(datas){ datas.forEach(function(item,i){ document.body.appendChild(item); }); }).catch(function(err){ console.log(err); })
///////Promise.resolve()
Promise.resolve(loadImg(imgs[0])).then(function(img){ document.body.appendChild(img); })
///////Promise.resolve()
Promise.resolve(loadImg(imgs[0])).then(function(img){ document.body.appendChild(img); })
以上。
ES6——異步操作之Promise