es6 async / await 使用經驗總結

async await使用的注意事項

    1. async await注意 不能捕獲Promise拋出的異常,所以我按下面的方法使用它

      async getPosterData(optType = 'search') {
          this.loading.table = true;
          let res = null;
          try {
              res = await api.getPosterData(param);
           } finally {
                    this.loading.table = false;
                    }
           }
      

也就是Promise進入catch函數時,如果這兩不捕獲這個異常,就會報錯。

  • 2.async await必須成對在一個函數裏使用,不能跨函數,如下是錯誤的

         async function test(){
                     [1,2,3].forEach( (item)=>{
                          await this.queryTable(item);//這個寫法是錯誤的
                    })
        }
    

正確的應該是

             function test(){
                   [1,2,3].forEach( async (item)=>{
                        await this.queryTable(item);//這個寫法纔對
                  })
              }
  • 3.async await不能跨多個函數實現同步效果,只能在一個函數內部使用同步執行的效果

        async function getData() {
                  console.log(1)
                 useSystemMaAppId();//未加await不能按照1,2,3,4,5輸出
                console.log(4)
                 await api.getPosterDetail({ id: this.id });
                console.log(5)
    
        }
         async function useSystemMaAppId() {
                console.log(2)
                 await api.getCustomPages()
               console.log(3)
    
           }
        //這樣不能按順序輸出 1.2.3.4,5
       //把getData下面這個樣子就可以同步輸出
            async function getData() {
                  console.log(1)
                await useSystemMaAppId();//添加 await 這樣可以按照 1,2,3,4,5的順序輸出
                console.log(4)
                 await api.getPosterDetail({ id: this.id });
                console.log(5)
    
        }
    
  • 4.async await標記的函數 返回值是一個pending狀態的Promise,而且返回值會成爲then回調的輸入參數

          async function useSystemMaAppId() {
                console.log(2)
                 await api.getCustomPages()
               console.log(3)
             return 'test';
           }
     console.log(' 返回結果查看',   useSystemMaAppId());//打印後看到返回的是一個pending狀態的Promise
     
             useSystemMaAppId().then(res=>{ console.log(res); })//打印出來的res爲 test.
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章