How to finish all fetch before executing next function in React?

后端 未结 3 1591
悲哀的现实
悲哀的现实 2021-02-01 04:06

Using ReactJS, I have two different API points that I am trying to get and restructure: students and scores. They are both an array of objects.

3条回答
  •  心在旅途
    2021-02-01 04:50

    Your code mixes continuation callbacks and Promises. You'll find it easier to reason about it you use one approach for async flow control. Let's use Promises, because fetch uses them.

    // Refactor getStudents and getScores to return  Promise for their response bodies
    function getStudents(){
      return fetch(`api/students`, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }).then((response) => response.json())
    };
    
    function getScores(){
      return fetch(`api/scores`, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }).then((response) => response.json())
    };
    
    // Request both students and scores in parallel and return a Promise for both values.
    // `Promise.all` returns a new Promise that resolves when all of its arguments resolve.
    function getStudentsAndScores(){
      return Promise.all([getStudents(), getScores()])
    }
    
    // When this Promise resolves, both values will be available.
    getStudentsAndScores()
      .then(([students, scores]) => {
        // both have loaded!
        console.log(students, scores);
      })
    

    As well as being simpler, this approach is more efficient because it makes both requests at the same time; your approach waited until the students were fetched before fetching the scores.

    See Promise.all on MDN

提交回复
热议问题