在让openDialog()
运行之前,让FetchJoke()
完成异步的正确用法是什么
async getrandomJoke(query: string){
this.fetchJoke(query);
this.openDialog();
}
更新:
问题是:即使使用了等待关键字,randomJoke: any;
在到达openDialog()
时也未定义
见下文:
async getrandomJoke(query: string)
{
await this.fetchJoke(query);
console.log(this.randomJoke + "var"); //Undefined.
this.openDialog();
}
fetchJoke(query: string){
this.apiService.randomJoke(query).subscribe(
(data =>
{
this.randomJoke = data;
console.log(this.randomJoke + "varinside");//[Object object]
}))
}
没有任何值被发送到Dialog((。因为它似乎在Fetchjoke()
完成之前运行
您需要让fetchJoke
返回一个承诺:
fetchJoke(query: string){
return firstValueFrom(this.apiService.randomJoke(query))
}
然后await
它!
async getrandomJoke(query: string){
const joke = await this.fetchJoke(query); // will wait for fetchJoke to finish to continue
this.openDialog(joke);
}
在这种情况下应该使用await:
async getrandomJoke(query: string){
await this.fetchJoke(query);
this.openDialog();
}