简体   繁体   English

从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 login-form-component.html

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

login-form-component.ts 登录表单组件.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. loginResponse将始终返回undefinied时,我想它返回的result对象。 I believe it has something to do with asynchronous methods. 我相信这与异步方法有关。 Can you help me out? 你能帮我吗? Thanks 谢谢

You should return the result from signInWithFacebook function: 您应该从signInWithFacebook函数返回结果:

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

your function doesn't return anything. 您的函数不返回任何内容。 And the try .. catch block doesn't work that way for Promises. try .. catch块对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 })
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM