简体   繁体   中英

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. I searched on how to do this and stumbled across async and await . 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. The "IN ASYNC FUNCTION" and "AFTER ASYNC" are executed but not the ones after/in my call on 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.

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()'):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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