简体   繁体   中英

How to make asynchronous calls inside a forEach() which depends on data from another asynchronous call?

I am working with an API and want to make some calls from my React application. They are async calls nested inside a forEach(). I get all the promises and push them inside a promises array. Then use the axios.all() method as described by axios docs but when I push the results of these promises to the myData array I get an empty array.

Except axios.all(promises) method I tried nested then() calls on Promises but that just complicated everything. Here is my code:

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

When I run the code I expect the array "myData" to be filled with the data pushed from the API call but instead I get an empty array. Is there any way to get around this problem?

// 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>

I guess this version is more handy.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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