Search code examples
javascripthtmlangularionic-frameworkes6-promise

Return a data out of a promise and get it in another method


I'm missing something on how to use async/await and probably promises methods too. Here is what I am trying to do:

login-form-component.html

<button (click)="sinInWithFacebook()">Sign In with Facebook</button>

login-form-component.ts

async sinInWithFacebook() {
  const loginResponse = await this.auth.signInWithFacebook();
  console.log(loginResponse); // it returns undefinied
}

auth.service

signInWithFacebook() {
  try {
    this.fb.login(['email'])
      .then((loginResponse: FacebookLoginResponse) => {
        const credential = firebase.auth.FacebookAuthProvider.credential(loginResponse.authResponse.accessToken);
      return <LoginResponse>{
        result: this.auth.auth.signInWithCredential(credential)
      }
    })
  }
  catch (e) {
    return {
      error: e
    }
  }

}

loginResponse will always returns undefinied when I want it to return the result object. I believe it has something to do with asynchronous methods. Can you help me out? Thanks


Solution

  • You should return the result from signInWithFacebook function:

        try {
          return this.fb.login(['email'])
            .then((loginResponse: FacebookLoginResponse) => {
              const credential = firebase.auth.FacebookAuthProvider.credential(loginResponse.authResponse.accessToken);
                return <LoginResponse>{
                  result: this.auth.auth.signInWithCredential(credential)
                }
            })
        }