簡體   English   中英

如何在打字稿中使用異步/等待

[英]How to use async/await in typescript

我想從我的ThemeService上調用http.get方法,並使其盡可能“同步”,以使其在從調用中獲取Theme后連續。 我搜索了如何執行此操作,偶然發現asyncawait 我嘗試實現此功能,但效果不佳。 我在代碼中放了一些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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM