title: How to wait for a function to finish its execution in angular 2.?
body: <p>Below is my code, I want <code>login()</code> and <code>authenticated()</code> functions to wait for <code>getProfile()</code> function to finish its execution. I tried several ways like promise etc. but I couldn't implement it. Please suggest me the solution.</p>
  
  <pre><code>import { Injectable }      from '@angular/core';
  import { tokenNotExpired } from 'angular2-jwt';
  import { myConfig }        from './auth.config';
  
  // Avoid name not found warnings
  declare var Auth0Lock: any;
  
  @Injectable()
  export class Auth {
    // Configure Auth0
    lock = new Auth0Lock(myConfig.clientID, myConfig.domain, {
      additionalSignUpFields: [{
        name: "address",                              // required
        placeholder: "enter your address",            // required
        icon: "https://example.com/address_icon.png", // optional
        validator: function(value) {                  // optional
          // only accept addresses with more than 10 chars
          return value.length &gt; 10;
        }
      }]
    });
  
    //Store profile object in auth class
    userProfile: any;
  
    constructor() {
      this.getProfile();  //I want here this function to finish its work
    }
  
  
    getProfile() {
      // Set userProfile attribute if already saved profile
      this.userProfile = JSON.parse(localStorage.getItem('profile'));
  
      // Add callback for lock `authenticated` event
      this.lock.on("authenticated", (authResult) =&gt; {
        localStorage.setItem('id_token', authResult.idToken);
  
        // Fetch profile information
        this.lock.getProfile(authResult.idToken, (error, profile) =&gt; {
          if (error) {
            // Handle error
            alert(error);
            return;
          }
  
          profile.user_metadata = profile.user_metadata || {};
          localStorage.setItem('profile', JSON.stringify(profile));
          this.userProfile = profile;
        });
      });
    };
  
    public login() {
      this.lock.show();
      this.getProfile();  //I want here this function to finish its work
    };
  
    public authenticated() {
      this.getProfile();  //I want here this function to finish its work
      return tokenNotExpired();
    };
  
    public logout() {
      // Remove token and profile from localStorage
      localStorage.removeItem('id_token');
      localStorage.removeItem('profile');
      this.userProfile = undefined;
    };
  }
  </code></pre>