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

后端 未结 3 1589
悲哀的现实
悲哀的现实 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:47

    I believe you need to wrap your functions in arrow functions. The functions are being invoked as the promise chain is being compiled and sent to the event loop. This is creating a race condition.

        function getStudentsAndScores(cbStudent, cbScores, cbStudentsScores){
      getStudents(cbStudent).then(() => getScores(cbScores)).then(cbStudentsScores);
    }
    

    I recommend this article for additional reading: We Have a Problem with Promises by Nolan Lawson

    And here's a repo I made that has an example for each of the concepts talked about in the article. Pinky Swear

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-02-01 04:54

    I would recommend restructuring slightly - instead of updating your state after each fetch call completes, wait for both to complete and then update the state all at once. you can then use the setState callback method to run the next method you would like to.

    You can use a Promise library such as Bluebird to wait for multiple fetch requests to finish before doing something else

    import Promise from 'bluebird'
    
    getStudents = () => {
      return fetch(`api/students`, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }).then(response => response.json());
    };
    
    getScores = () => {
      return fetch(`api/scores`, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
      }).then(response => response.json());
    };
    
    Promise.join(getStudents(), getScores(), (students, scores) => {
        this.setState({
            students,
            scores
        }, this.rearrangeStudentsWithScores);
    });
    
    0 讨论(0)
提交回复
热议问题