简体   繁体   English

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

[英]How to use async/await in typescript

I want to call a http.get method off my ThemeService and make it as "synchronous" as possible so that it continuous after it gets Theme from the call. 我想从我的ThemeService上调用http.get方法,并使其尽可能“同步”,以使其在从调用中获取Theme后连续。 I searched on how to do this and stumbled across async and await . 我搜索了如何执行此操作,偶然发现asyncawait I tried to implement this but it didn't quite work. 我尝试实现此功能,但效果不佳。 I put some console.log() in the code so i can see what is and what isn't executed. 我在代码中放了一些console.log() ,这样我就可以看到执行了什么,没有执行什么。 The "IN ASYNC FUNCTION" and "AFTER ASYNC" are executed but not the ones after/in my call on ThemeService . 执行“ IN ASYNC FUNCTION”和“ AFTER ASYNC”,但不执行我在ThemeService调用之后/之后的那些。

Because i am new to the async/await functions in typescript i don't know if what I have written is badly or if what i'm trying to do is possible or not. 因为我是打字稿中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");
}

You can have it like this (note usage of 'take(1).toPromise()'): 您可以像这样(注意“ 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");
}

Or a bit shorter: 或更短:

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");
    }
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM