鍍金池/ 問答/HTML/ 關(guān)于promise.all處理reject求助

關(guān)于promise.all處理reject求助

 let resultData = []
        try {
          resultData = await Promise.all([
            this.get(API.getCustomSpeech),
            this.get(API.getUserConfiguration),
            this.post((API.getFirstConvList))
          ])
        }catch(e){
          console.log(e)
        }

正常情況下resultData是包含三個正確返回結(jié)果的數(shù)組,但是,當(dāng)某一個網(wǎng)絡(luò)請求返回reject時,我在node8下測試的結(jié)果是,流程走到catch中,且只返回對應(yīng)的reject,丟失了其他2個正常的返回結(jié)果。

想要的結(jié)果是:
能夠拿到2個resolve和一個reject。我在catch對reject做錯誤處理。

promisen能做到嗎?

回答
編輯回答
夢若殤

@nurdun

這樣寫,將2個本來異步的操作變成了同步: 先tet后data,我們需要一種更好的方法,讓tet和data異步執(zhí)行,promise.all接受2個異步的結(jié)果,無論是否正確返回,返回的數(shù)據(jù)都應(yīng)該保存在promise.all的結(jié)果數(shù)組中。

或許可以這么做:

toFetch(url){
    return fetch(url)
        .then(res=>res.json())
        .catch(err=>new Promise(resolve=>resolve(err)))

將err結(jié)果也封裝成resolve返回,這樣,所有返回都在promise.all中。

2018年1月20日 13:03
編輯回答
乖乖瀦

關(guān)于promise.all()這種問題確實存在的,可能又解決方法,但是我個人更喜歡用這種方式,你可以參考一下

toFetch(url){
    return fetch(url)
    .then(res=>res.json())
    .catch(er=>er)
  }

  async getData(){
    let user = await this.toFetch('tet.json');
    console.log("name: "+user.name);
    let data = await this.toFetch('data.json');
    console.log("name: "+data.time);
  }
2018年4月20日 21:12