从promise中返回数据并以另一种方法获取

时间:2018-02-26 10:43:00

标签: javascript html angular ionic-framework es6-promise

我遗漏了一些关于如何使用async / await的东西,也可能是承诺方法。 这是我想要做的:

登录外形component.html

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

登录外形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对象时,

undefinied将始终返回result。我相信它与异步方法有关。你能帮我吗? 感谢

1 个答案:

答案 0 :(得分:1)

你的功能不会返回任何内容。并且try .. catch块对Promise不起作用。

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