首页 > 解决方案 > 如何保持获取队列有序

问题描述

我一页还有两个抓取请求,如何一一排列?

例如,只是一个代码,期望获取队列以 num 顺序执行。

class FetchingQueue extends Component {
  ...
  componentDidUpdate(preProps) {
    if ( this.props.prop1 != preProps.props1) {
      this.props.fetching1
      this.props.fetching2
      this.timeoutHanlde = setTimeout(() => {
        this.props.fetching3
      }, 1000)
    }
  }
  render() {
    return (
      ...
    )
  }
}
export default connect(
  state => ({
    prop1: state.reducer.props1
  }),
  { fetching1, fetching2, fetching3 }
)(FetchingQueue)

标签: javascriptreactjsreact-redux

解决方案


只需从获取函数中返回 Promises,然后等待它们:

class FetchingQueue extends Component {
  ...
  async componentDidMount() {
    const fetching1Result = await this.props.fetching1();
    const fetching2Result = await this.props.fetching2();
    const fetching3Result = await this.props.fetching3();
  }

  render() {
    return (
      ...
    )
  }
}

export default connect(
  state => ({ prop1: state.reducer.props1 }),
  { fetching1, fetching2, fetching3 }
)(FetchingQueue)

获取函数可能如下所示:

const fetching1 = new Promise((resolve, reject) => {
  // call resolve when ready
  resolve('result');
});

推荐阅读