【问题标题】:Passing down the result of a promise传递承诺的结果
【发布时间】:2017-08-04 22:38:03
【问题描述】:

所以在我的反应代码中我有这个:

  componentDidMount = () => {
    firebase.auth().getRedirectResult().then(function(result) {
        if (result.credential) {
          var token = result.credential.accessToken;
        }
        var ruser = result.user;
        console.log(ruser.displayName, 'lol'); //THIS LOGS CORRECTLY
      }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        var email = error.email;
        var credential = error.credential;
      }).then(function(result){
        this.setState({user: ruser});
        console.log(result, 'rslt'); //THIS LOGS UNDEFINED 
      });

  }

我基本上想设置登录用户的状态。但是,当我把它传递下来时,我得到了未定义,我在承诺方面做错了什么?我只想传递结果并使其在函数范围之外可用...

【问题讨论】:

  • 您可能需要在您的第一个 then 中使用 return result/ruser
  • 另外,this 不会在您最后的 then 回调中定义。您需要使用箭头函数或将this 绑定到回调。

标签: javascript reactjs firebase promise firebase-authentication


【解决方案1】:

除非你返回你声明的内容,否则来自承诺中的声明是没有意义的——如果你想传递它,你必须返回result

componentDidMount = () => {
  firebase.auth().getRedirectResult().then(function(result) {
      if (result.credential) {
        var token = result.credential.accessToken;
      }

      console.log(result.user.displayName, 'displayName');

      return result; // this will be passed down
    }).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
      var email = error.email;
      var credential = error.credential;
    }).then(result => {
      this.setState({user: result.user});

      console.log(result.user, 'user'); 
    });
}

另外 - 正如 nils 提到的,您必须在最后一个 .then 中使用 arrow function 才能使用父级的上下文,它是 setState

【讨论】:

  • 别忘了在catch 回调中也给return 一些有意义的东西——或者把它移到最后
猜你喜欢
  • 2018-03-18
  • 2017-11-28
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-17
  • 2017-10-18
  • 1970-01-01
相关资源
最近更新 更多