如何在依赖于另一个异步调用数据的forEach()内部进行异步调用?

时间:2018-12-29 20:43:12

标签: javascript reactjs asynchronous axios

我正在使用API​​,并且想从我的React应用程序中进行一些调用。它们是嵌套在forEach()中的异步调用。我得到了所有的承诺,并将它们放入一个promises数组中。然后使用axios文档所述的axios.all()方法,但是当我将这些promise的结果推送到myData数组时,我得到一个空数组。

除了axios.all(promises)方法,我尝试了嵌套的then()调用Promises,但这使所有事情变得复杂。这是我的代码:

componentDidUpdate(nextProps, nextState) {
    if (this.props.to !== nextProps.to || this.props.from !== 
nextProps.from) {
  let promises = [];
  Axios.get(
    `http://localhost:3000/api/visits?from=${this.props.from}&to=${
      this.props.to
    }`
  ).then(res => {
    res.data.forEach(visit => {
      promises.push(
        Axios.get(`http://localhost:3000/api/clients/${visit.clientId}`
        })
      );
    });
    Axios.all(promises).then(results => {
      results.forEach(res => {
        const clientProps = {
          name: res.data[0].name,
          lastname: res.data[0].lastname,
          mobile_number: res.data[0].mobile_number
        };
        myData.push(clientProps); // Here I am pushing the data to a global array
      });
this.setState({myData})
    });
  });
 }
}

当我运行代码时,我期望数组“ myData”填充有从API调用推送的数据,但是我得到了一个空数组。有什么办法可以解决这个问题?

// I try to access data from this.state inside the render() method of my class component to generate a Table data with the name property.

 <td>{this.state.myData[index].name}</td>

2 个答案:

答案 0 :(得分:0)

我想这个版本比较方便。

componentDidUpdate(nextProps, nextState) {
    if (this.props.to !== nextProps.to || this.props.from !== 
nextProps.from) {
  let promises = [];
  Axios.get(
    `http://localhost:3000/api/visits?from=${this.props.from}&to=${
      this.props.to
    }`
  ).then(res => {
    return Axios.all(res.data.map(visit => {
      return Axios.get(`http://localhost:3000/api/clients/${visit.clientId}`)
    }))
  })
  .then(results => {
      return results.map(res => {
          return {
          name: res.data[0].name,
          lastname: res.data[0].lastname,
          mobile_number: res.data[0].mobile_number
        };
      });
    })
  .then(clientProps => {
    // then update state or dispatch an action
    this.setState(() => ({myData: clientProps}));
  });

}
}

答案 1 :(得分:0)

getVisits(from, to) {
  return Axios.get(`http://localhost:3000/api/visits?from=${from}&to=${to}`);
}

getClients(ids) {
  return Axios.all(ids.map(id => Axios.get(`http://localhost:3000/api/clients/${id}`));
}

async getClientsOfVisits(from, to) {
  const response = await this.getVisits(from, to);
  const promises = await this.getClients(response.data.map(visit => visit.clientId)));

  return promises.map(res => res.data[0]);
}

componentDidUpdate(nextProps, nextState) {
  const { to, from } = this.props;
  const toChanged = to !== nextProps.to;
  const fromChanged = from !== nextProps.from;

  if (toChanged || fromChanged) {
    this.getClientsOfVisits(to, from).then(myData => {
      this.setState({ myData });
    })
  }
}