Promise 並行
Promise.all是所有的Promise執行完畢后(reject|resolve)返回一個Promise對象。最近在開發一個項目中,需要等接口拿到全部數據后刷新頁面,取消loding效果
// 項目中請求接口 function getShowProject(resolve, reject) { $.ajax({ url: `${api}/rrz/member/showProjectById`, type: 'get', data: { appId: appId }, success: function (res) { if (res.result == 'success') { gather['listBy'] = res.data; resolve(); } } }); } function getProjectPic(resolve, reject) { ... } function projectRelation(resolve, reject) { ... } function queryProjectDynamicS(resolve, reject) { ... } function showProjectLoveValue(resolve, reject) { ... } function getAppProjectDonorComment(resolve, reject) { ... } // 等待接口全部請求完成后 刷新頁面 var a1 = new Promise(getShowProject); var a2 = new Promise(getProjectPic); var a3 = new Promise(projectRelation); var a4 = new Promise(queryProjectDynamicS); var a5 = new Promise(showProjectLoveValue); var a6 = new Promise(getAppProjectDonorComment); Promise.all([a1, a2, a2, a3, a4, a5, a6]).then(function () { info = { data: gather } getDetail(); console.log('loading效果圖消失'); })
廣州品牌設計公司https://www.houdianzi.com PPT模板下載大全https://redbox.wode007.com
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 // 最后執行