【问题标题】:.then is called before async function returns a value.then 在异步函数返回值之前调用
【发布时间】:2018-12-07 19:48:58
【问题描述】:

我正在尝试从 API 端点检索 authConfig。在我的应用组件中,我向服务请求该功能。

this.userDetailService.getAuthConfig().then(config => {
      this.oauthService.configure(config);
      this.oauthService.initAuthorizationCodeFlow();
    }); 

然后在我的服务中,auth 配置被设置并返回到应用程序组件。我在getAuthConfig 上使用.then,所以配置对象是存在的,当我需要它来配置oauthService 时。当我调试它时,我看到.configure 是用一个空对象调用的。为什么在 getAuthConfig 返回值之前调用 configure?

 getEnvs(): Promise<any> {
      return this.http.get('/backend').toPromise();
    }

 async getAuthConfig(): Promise<any> {
      this.getEnvs().then((data) => {
        const env = data.env;
        const authConfig: AuthConfig = {
          loginUrl: env.authorizationEndpoint,
          redirectUri: env.redirectUris,
          clientId: env.clientId,
          scope: '',
          oidc: false
        };
        return (authConfig);
      });
    }

【问题讨论】:

  • 不要将thenawait 承诺风格混用。

标签: javascript typescript promise async-await


【解决方案1】:

您需要从getAuthConfig 返回创建的promise,以便getAuthConfig 的调用者可以正确等待getAuthConfig 中生成的promise 链:

 async getAuthConfig(): Promise<any> {
     return this.getEnvs().then((data) => {
   //^^^^^^
       // ...
     })

你可以在同一个类中的另一个异步方法中使用它:

async whatever() {
  // this will now await for the promise chain  
  // within getAuthConfig and return the result
  const authConfig = await this.getAuthConfig();
}

由于getAuthConfig 是一个异步函数,您可以选择利用它来清理它:

async getAuthConfig(): Promise<AuthConfig> {
  const { env } = await this.getEnvs();
  return {
    loginUrl: env.authorizationEndpoint,
    redirectUri: env.redirectUris,
    clientId: env.clientId,
    scope: '',
    oidc: false
  };
}

【讨论】:

  • 我还需要返回 (authConfig) 还是返回 getAuthConfig 就足够了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 2021-05-15
  • 2019-08-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
相关资源
最近更新 更多