Does it matter if the function calls in this loop run concurrently? And if so, how do I make each wait until previous is done?

Tags: , ,



This code works as expected now, but as my app loads, I am doing API calls to gather data from 8 different tables. I notice that all the calls are happening almost simultaneously and out of order. Order doesn’t actually matter as long as they all happen, as I’m just loading data.

I’m just trying to think are there drawbacks to doing it this way that I need to watch out for, and if so, how do I make the loop wait until the function is finished, to then move onto the next iteration through the loop?

componentDidMount() {
    const tableSections = [
      'audit_general',
      'audit_culture',
      'audit_performance',
      'audit_policies',
      'audit_risk',
      'audit_strategy',
      'audit_rewards',
      'audit_workforce'
    ];
    for (let i = 0; i < tableSections.length; i++){
      this.grabTableData(tableSections[i]);
    }
  }

  grabTableData(tableName) {
    fetch(API_URL + `/responses/${tableName}/${this.props.employeeId}`)
      .then((res) => {
        if (!res.ok) {
          throw new Error();
        }
        return res.json();
      })
      .then((result) => {
        this.setState({
          ...result[0],
        });
      })
      .catch((error) => {
        console.log(error);
      });
  }

Answer

componentDidMount() {
    const tableSections = [
      'audit_general',
      'audit_culture',
      'audit_performance',
      'audit_policies',
      'audit_risk',
      'audit_strategy',
      'audit_rewards',
      'audit_workforce'
    ];
    for (let i = 0; i < tableSections.length; i++){
      this.grabTableData(tableSections[i]);
    }
  }

  async grabTableData (tableName) {
    await fetch(API_URL + `/responses/${tableName}/${this.props.employeeId}`)
      .then((res) => {
        if (!res.ok) {
          throw new Error();
        }
        return res.json();
      })
      .then((result) => {
        this.setState({
          ...result[0],
        });
      })
      .catch((error) => {
        console.log(error);
      });
  }


Source: stackoverflow