angular - Angular 8 中的异步/等待无法按预期工作
问题描述
我习惯在 Asp.net 中使用 async/await。我现在需要在 ngBootstrap 模态服务中进行几次 API 调用 (4)。用户将单击一个按钮来打开一个模态。第一个 API 调用获取 Modal 所需的基本信息。async OpenModal() 方法用 async 修饰,第一个 API 调用使用 async res 如下所示。
this.service.findContent(id).subscribe(
async res => {
//other code
var socialDataResult = await this.getSocialData();
console.log('socialDataResult ', socialDataResult);
//other code
},
async getSocialData() {
let result: SocialData;
this.socialDataService.findSocialData().subscribe(
async res => {
let socialData = new SocialData(res);
console.log('socialData ', socialData);
result = socialData;
return result;
},
err => {
console.log(err);
}
)
return result;
}
我希望代码在写入控制台之前会等待从 getSocialData 返回的响应。照原样,它将控制台日志写入调用方法的正下方,然后将控制台日志写入被调用的方法。调用方法中的控制台日志显示“未定义”。被调用方法中的控制台日志显示了包含所有数据的 SocialData 对象。
同样重要的是要注意,当我将鼠标悬停在 await this.getSocialData(); 上时,我明白了。
(method) ContentComponent.getSocialData(): Promise<SocialData>
任何帮助深表感谢。谢谢!
解决方案
getSocialData
说它是async
,但它实际上从未等待任何东西。如果您没有利用 Observables 的任何高级功能,最好将结果转换findSocialData()
为 Promise。
async getSocialData() {
try {
let res = await this.socialDataService.findSocialData().toPromise();
let socialData = new SocialData(res);
console.log('socialData ', socialData);
return socialData;
} catch(err) {
console.log(err); // you might not actually want to eat this exception.
}
}
推荐阅读
- laravel - 具有相同基础项目的 git-versioning 下的 Laravel 项目
- python - 通过在条件上设置变量手动编写 django 迁移
- c# - 如何使用 c# 应用程序代码将文件从 TFS 下载到我们的本地文件夹?
- python - 将带有编号方案的变量附加到列表时出现问题
- selenium - 定义要在运行时使用的 Chromedriver
- gitlab - GitLab CI Build 未上传代码接收工件
- php - Yii框架无法连接数据库
- c - '无效读取大小 8' - Valgrind。试图用来自其他结构的数据填充结构
- excel - 隐藏整行并在完成后取消隐藏
- beautifulsoup - 在 BeautifulSoup 中查找特定跨度标签的计数