Want to finish all fetch before executing next function in React? 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | // 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); }) |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.