Promise.all是全部的Promise執行完畢後(reject|resolve)返回一個Promise對象。ajax
最近在開發一個項目中,須要等接口拿到所有數據後刷新頁面,取消loding效果api
1 // 項目中請求接口 2 function getShowProject(resolve, reject) { 3 $.ajax({ 4 url: `${api}/rrz/member/showProjectById`, 5 type: 'get', 6 data: { appId: appId }, 7 success: function (res) { 8 if (res.result == 'success') { 9 gather['listBy'] = res.data; 10 resolve(); 11 } 12 } 13 }); 14 } 15 function getProjectPic(resolve, reject) { 16 ... 17 } 18 function projectRelation(resolve, reject) { 19 ... 20 } 21 function queryProjectDynamicS(resolve, reject) { 22 ... 23 } 24 function showProjectLoveValue(resolve, reject) { 25 ... 26 } 27 function getAppProjectDonorComment(resolve, reject) { 28 ... 29 } 30 // 等待接口所有請求完成後 刷新頁面 31 var a1 = new Promise(getShowProject); 32 var a2 = new Promise(getProjectPic); 33 var a3 = new Promise(projectRelation); 34 var a4 = new Promise(queryProjectDynamicS); 35 var a5 = new Promise(showProjectLoveValue); 36 var a6 = new Promise(getAppProjectDonorComment); 37 Promise.all([a1, a2, a2, a3, a4, a5, a6]).then(function () { 38 info = { data: gather } 39 getDetail(); 40 console.log('loading效果圖消失'); 41 })
在項目的實際操做中會用到串行調用方法的狀況,實現異步執行,例如
有三個方法,方法1、方法2、方法三,須要執行完方法一以後執行方法二,執行完方法二以後執行方法三,能夠用Promise實現,簡單的模擬作法以下:
promise
function one(){ console.log(11111); } function two(){ console.log(22222); } function three(){ console.log(33333); } function fiveP(func){ return new Promise(function(resolve, reject) { func(); resolve(); }); } p.then(fiveP(one)) .then(fiveP(three)) .then(fiveP(two)) .then(function(result) { console.log('最後執行' + result); }); // 執行結果 // 1111 // 3333 // 2222 // 最後執行