gpt4 book ai didi

asynchronous - 如何在 typescript 中使用异步/等待

转载 作者:搜寻专家 更新时间:2023-10-30 21:30:58 25 4
gpt4 key购买 nike

我想从我的 ThemeService 调用一个 http.get 方法并使其尽可能“同步”,以便它在获取 Theme< 后继续 来自电话。我搜索了如何执行此操作并偶然发现了 asyncawait。我试图实现这一点,但效果不佳。我在代码中放置了一些 console.log(),这样我就可以看到哪些已执行,哪些未执行。 “IN ASYNC FUNCTION”和“AFTER ASYNC”会被执行,但不会在我调用 ThemeService 之后/中执行。

因为我是 typescript 中 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");
}
}

希望这对您有所帮助。

关于asynchronous - 如何在 typescript 中使用异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36097111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com