KevinTale
KevinTale

Reputation: 1858

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

Upvotes: 0

Views: 429

Answers (2)

Thomas
Thomas

Reputation: 12637

your function doesn't return anything. And the try .. catch block doesn't work that way for Promises.

signInWithFacebook():Promise<LoginResponse> {
  return this.fb.login(['email'])
    .then((loginResponse: FacebookLoginResponse) => {
      const credential = firebase.auth.FacebookAuthProvider.credential(loginResponse.authResponse.accessToken);
      //my guts tell me that `this.auth.auth.signInWithCredential` is async as well.
      //so let the promise chain deal with that/resolve that
      return this.auth.auth.signInWithCredential(credential);
    })
    .then(
      result => ({ result }),
      error => ({ error })
    );
}

Upvotes: 1

Sergii Vorobei
Sergii Vorobei

Reputation: 1487

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

Upvotes: 1

Related Questions