且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在React中执行下一个功能之前完成所有提取?

更新时间:2022-06-10 23:22:16

您的代码混合了继续回调和承诺.您会发现使用一种异步流控制方法更容易对此进行推理.让我们使用Promises,因为fetch使用它们.

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.

请参阅MDN上的 Promise.all

See Promise.all on MDN