Async/await 在 Angular 8 中未按预期工作

Dum*_*an2 3 angular

我习惯在Asp.net中使用async/await。我现在需要在 ngBootstrap Modal Service 中进行多个 API 调用 (4)。用户将单击按钮来打开模态框。第一个 API 调用获取 Modal 所需的基本信息。异步 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;

      }
Run Code Online (Sandbox Code Playgroud)

我希望代码在写入控制台之前会等待从 getSocialData 返回的响应。按原样,它会在调用方法的正下方写入控制台日志,然后再将控制台日志写入被调用的方法中。调用方法中的控制台日志显示“未定义”。被调用方法中的控制台日志显示包含所有数据的 SocialData 对象。

同样重要的是要注意,当我将鼠标悬停在 wait this.getSocialData(); 上时,我得到了这个。

(method) ContentComponent.getSocialData(): Promise<SocialData>
Run Code Online (Sandbox Code Playgroud)

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

Str*_*ior 5

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.
    }
}
Run Code Online (Sandbox Code Playgroud)