[英]How to use async/await in typescript
我想從我的ThemeService
上調用http.get
方法,並使其盡可能“同步”,以使其在從調用中獲取Theme
后連續。 我搜索了如何執行此操作,偶然發現async
和await
。 我嘗試實現此功能,但效果不佳。 我在代碼中放了一些console.log()
,這樣我就可以看到執行了什么,沒有執行什么。 執行“ IN ASYNC FUNCTION”和“ AFTER ASYNC”,但不執行我在ThemeService
調用之后/之后的那些。
因為我是打字稿中async/await
功能的新手,所以我不知道我寫的東西不好還是我想做的事情是否可行。
ngOnInit():void{
let id = +this.routeParams.get('themeId');
async function getTheme(){
console.log("IN ASYNC FUNCTION");
var val = await this.themeService.getTheme(id).subscribe((theme:Theme)=> {
this.theme = theme;
console.log("IN AWAIT FUNCTION")
});
console.log("AFTER AWAIT");
return val;
}
getTheme();
console.log("AFTER ASYNC");
}
您可以像這樣(注意“ take(1).toPromise()”的用法):
ngOnInit():void
{
let id = +this.routeParams.get('themeId');
async function getTheme()
{
console.log("IN ASYNC FUNCTION");
var val = await this.themeService.getTheme(id).take(1).toPromise();
console.log("AFTER AWAIT");
return val;
}
this.theme = await getTheme();
console.log("AFTER ASYNC");
}
或更短:
class MyComponent implements OnInit
{
async ngOnInit()
{
let id = +this.routeParams.get('themeId');
this.theme = await this.themeService.getTheme(id).take(1).toPromise();
console.log("AFTER ASYNC");
}
}
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.