2017-05-07 36 views
1

等待在es7中是一個了不起的功能。是否可以在Js中使用await而無需異步

但是,每次我使用await,我發現我必須定義一個異步函數並調用此函數。

async function asy(){ 
     const [resCityGuess,resCityHot,resCityAll]=await Promise.all([ 
         this.http.get('api/v1/cities?type=guess'), 
         this.http.get('api/v1/cities?type=hot'), 
         this.http.get('api/v1/cities?type=group') 
     ]) 
     this.cityGuessName=resCityGuess.data.name; 
     this.cityGuessId=resCityGuess.data.id; 
     this.cityHot=resCityHot.data; 
     this.cityAll=resCityAll.data; 
    } 
    asy.apply(this); 

我要的是使用等待沒有異步功能,如

 // the async function definition is deleted 
     const [resCityGuess,resCityHot,resCityAll]=await Promise.all([ 
         this.http.get('api/v1/cities?type=guess'), 
         this.http.get('api/v1/cities?type=hot'), 
         this.http.get('api/v1/cities?type=group') 
     ]) 
     this.cityGuessName=resCityGuess.data.name; 
     this.cityGuessId=resCityGuess.data.id; 
     this.cityHot=resCityHot.data; 
     this.cityAll=resCityAll.data; 
     // without call fn 

我覺得定義函數fn並稱之爲FN有時會重複,所以我想知道的是有可能優化情況嗎?

我可以使用await而不使用異步嗎?

非常感謝!

+1

我不知道你在等什麼,但是它是一個等待異步調用返回的關鍵字,所以你的問題是毫無意義的。 –

+1

你的問題的答案是否定的,但如果你只使用一次函數,你可能想看看IIFE的(立即調用函數表達式) –

+0

@GabeRogan我認爲這是一個解決方案.Thx –

回答

5

編號await運營商只有在async函數有意義。

+0

Thx。我想用IIFE來幫助我。 –

+2

@曾志強yes,你可以這樣做:'(async function(){...; await x(); ...})();' – Pointy

+1

這個文檔對理解原因有很大的幫助:https:// developer .mozilla.org/EN-US /文檔/網絡/的JavaScript /參考/運營/等待 – craftsman

相關問題