Fabio ha
Fabio ha

Reputation: 583

.then is called before async function returns a value

I am trying to retrieve the authConfig from an API-endpoint. Inside my app component, I request the function from a service.

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

Then in my service, the auth configs are set up and returned to the app component. I use .then on getAuthConfig, so the config-object is existing, when I need it to configure the oauthService. When I debug it, I see that .configure is called with an empty object. Why is configure called, before getAuthConfig returns a vaule?

 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);
      });
    }

Upvotes: 1

Views: 126

Answers (1)

nem035
nem035

Reputation: 35491

You need to return the created promise from getAuthConfig so the caller of getAuthConfig can correctly await the promises chain generated within getAuthConfig:

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

You would use it in another async method within the same class as:

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

Since getAuthConfig is an async function, you could optionally clean it up by taking advantage of that:

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

Upvotes: 2

Related Questions