等待在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而不使用異步嗎?
非常感謝!
我不知道你在等什麼,但是它是一個等待異步調用返回的關鍵字,所以你的問題是毫無意義的。 –
你的問題的答案是否定的,但如果你只使用一次函數,你可能想看看IIFE的(立即調用函數表達式) –
@GabeRogan我認爲這是一個解決方案.Thx –