首页 > 解决方案 > 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>

任何帮助深表感谢。谢谢!

标签: angular

解决方案


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.
    }
}

推荐阅读