ES6 Promise 并行執(zhí)行和順序執(zhí)行

更多例子

1.Promise.all 并行執(zhí)行promise

getA和getB并行執(zhí)行,然后輸出結(jié)果。如果有一個錯誤,就拋出錯誤

/**
 * 每一個promise都必須返回resolve結(jié)果才正確
 * 每一個promise都不處理錯誤
 */

const getA = new Promise((resolve, reject) => {
   //模擬異步任務(wù)
   setTimeout(function(){
     resolve(2);
   }, 1000) 
})
.then(result => result)


const getB = new Promise((resolve, reject) => {
   setTimeout(function(){
     // resolve(3);
     reject('Error in getB');
   }, 1000) 
})
.then(result => result)


Promise.all([getA, getB]).then(data=>{
    console.log(data)
})
.catch(e => console.log(e));

getA和getB并行執(zhí)行,然后輸出結(jié)果。總是返回resolve結(jié)果

/**
 * 每一個promise自己處理錯誤
 */

const getA = new Promise((resolve, reject) => {
   //模擬異步任務(wù)
   setTimeout(function(){
     resolve(2);
   }, 1000) 
})
.then(result => result)
.catch(e=>{

})


const getB = new Promise((resolve, reject) => {
   setTimeout(function(){
     // resolve(3);
     reject('Error in getB');
   }, 1000) 
})
.then(result => result)
.catch(e=>e)


Promise.all([getA, getB]).then(data=>{
    console.log(data)
})
.catch(e => console.log(e));

2.順序執(zhí)行promise

先getA然后getB執(zhí)行,最后addAB

  • 2.1 方法一——連續(xù)使用then鏈?zhǔn)讲僮?/li>
function getA(){
      return  new Promise(function(resolve, reject){ 
      setTimeout(function(){     
            resolve(2);
        }, 1000);
    });
}
 
function getB(){
    return  new Promise(function(resolve, reject){       
        setTimeout(function(){
            resolve(3);
        }, 1000);
    });
}
 
function addAB(a,b){
    return a+b
}

function getResult(){
    var  obj={};
    Promise.resolve().then(function(){
        return  getA() 
    })
    .then(function(a){
         obj.a=a;
    })
    .then(function(){
        return getB() 
    })
    .then(function(b){
         obj.b=b;
         return obj;
    })
    .then(function(obj){
       return  addAB(obj['a'],obj['b'])
    })
    .then(data=>{
        console.log(data)
    })
    .catch(e => console.log(e));

}
getResult();
  • 2.2 方法二——使用promise構(gòu)建隊列
function getResult(){
    var res=[];
    // 構(gòu)建隊列
    function queue(arr) {
      var sequence = Promise.resolve();
      arr.forEach(function (item) {
        sequence = sequence.then(item).then(data=>{
            res.push(data);
            return res
        })
      })
      return sequence
    }

    // 執(zhí)行隊列
    queue([getA,getB]).then(data=>{
        return addAB(data[0],data[1])
    })
    .then(data => {
        console.log(data)
    })
    .catch(e => console.log(e));

}

getResult();
  • 2.3方法三——使用async、await實現(xiàn)類似同步編程
function getResult(){
 async function queue(arr) {
  let res = []
  for (let fn of arr) {
    var data= await fn();
    res.push(data);
  }
  return await res
}

queue([getA,getB])
  .then(data => {
    return addAB(data[0],data[1])
  }).then(data=>console.log(data))

}

3. 總結(jié)

實現(xiàn)異步隊列函數(shù)的三種方式

方法一——連續(xù)使用then鏈?zhǔn)讲僮?br> 方法二——使用promise構(gòu)建隊列
方法三——使用async、await實現(xiàn)類似同步編程,async函數(shù)內(nèi)部實現(xiàn)同步


參考

Promise的順序執(zhí)行和并行執(zhí)行
構(gòu)建Promise隊列實現(xiàn)異步函數(shù)順序執(zhí)行


補(bǔ)充

ES6 Promise中斷
中斷或取消Promise鏈的可行方案

(1)reject()
(2)throw new Error()
一般來說,不要在then方法里面定義 reject 狀態(tài)的回調(diào)函數(shù)(即then的第二個參數(shù)),總是使用catch方法。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,351評論 25 708
  • 用兩張圖告訴你,為什么你的 App 會卡頓? - Android - 掘金 Cover 有什么料? 從這篇文章中你...
    hw1212閱讀 14,120評論 2 59
  • (轉(zhuǎn))原文鏈接:https://blog.csdn.net/huangqili1314/article/detai...
    谷哥得小弟閱讀 3,967評論 0 66
  • 作者: kim先生 來源: 自創(chuàng) 今天我們講的是ES6中的Promise這個異步操作對象。在學(xué)習(xí)Promise之前...
    前端進(jìn)階體驗閱讀 821評論 0 0
  • 每年的年初我們都會給自己設(shè)下很多規(guī)劃,比如說考軟件工程師證,認(rèn)真學(xué)習(xí)啞語,每周臨摹一幅畫,發(fā)布一篇英文語音,一月...
    子悠的南山閱讀 327評論 0 0

友情鏈接更多精彩內(nèi)容