setstate然后在REST API中响应

时间:2019-02-09 09:21:19

标签: javascript reactjs

recentTransactionsRecipientrecentTransactionsSender不为空时,我想将isLoading状态更改为true。

那么我想做个承诺

  componentDidMount() {
    this.Auth.recentTransactionsRecipient(this.props.id)
      .then(res => {
        if (res) {
          this.setState({
            recentTransactionsRecipient: res,
          });
        }
      })
      .catch(() => {
        /* just ignore */
      });

    this.Auth.recentTransactionsSender(this.props.id)
      .then(res => {
        if (res) {
          this.setState({
            recentTransactionsSender: res,
          });
        }
      })
      .catch(() => {
        /* just ignore */
      });
  }

2 个答案:

答案 0 :(得分:1)

尝试使用Promise.all()See MDN doc

  

Promise.all()方法返回一个Promise,当作为可迭代对象传递的所有promise已解决或可迭代对象不包含promise时,该Promise进行解析。它以第一个承诺被拒绝的理由拒绝。

Promise.all([promise1, promise2]).then((values) => {
  console.log(values);
  this.setState({
    recentTransactionsRecipient: values[0],
    recentTransactionsSender: values[1],
    isLoading: false
  });
});

答案 1 :(得分:0)

使用Promise.all()在这里效果很好,因为它允许您将多个输入承诺减少为一个承诺。 Promise.all()返回的单个promise是实现组件的isLoading : true状态更新逻辑的地方。

需要注意的重要细节;鉴于您的代码要求忽略Auth中的任何错误(以及Promise.all() to reject if any promise passed to it is rejected的行为),因此您需要在代码中予以说明。

一种可能性是引入一个辅助函数,该函数将“吸收”被拒绝的承诺,以使被拒绝的承诺不会传播到Promise.all()(这将导致您随后的setState()被跳过):

componentDidMount() {
    
    /*
    Locally defined helper method to absorb failure/rejection of the supplied promise
    */
    const ignoreIfRejected = (promise) => {
      
      return promise().catch(() => {
        console.info('A promise failed. Ignoring.');
      });
    }
    
    /* 
    The Promise returned from Promise.all will reject if any one of the promises in
    the passed array fails. Wrap each promise in locally defined ignoreIfRejected()
    helper to "absorb" any such error 
    */
    Promise.all([
      ignoreIfRejected(this.Auth.recentTransactionsRecipient(this.props.id)),
      ignoreIfRejected(this.Auth.recentTransactionsSender(this.props.id))
    ])
    .then((recipient, sender) => {
      
      if( recipient !== null && sender !== null) {
        
        /* 
        If resolved response from both promises returns non-null value
        then set isLoading state to true as required in post 
        */
        this.setState({ 
          recentTransactionsSender : sender,
          recentTransactionsRecipient : recipient,
          isLoading : false 
        });
      }      
    });
  }