getGrades() {
let grades = {};
this.state.courses.map((course) => {
this.state.studentDetails.map((student) => {
request.get(`http://localhost:8080/user/${student.id}/grades`).then((response) => {
if (response) {
response.body.map((grade) => {
grades[`${student.id}_${course.id}_${grade.gradeType}`] = grade.grade;
});
}
});
});
});
this.setState({grades: grades});
}
我希望只有在收集了所有信息时才会调用this.setState({grades: grades});
。我怎么能这样做?
答案 0 :(得分:1)
你需要按相反的顺序进行。
-
getGrades() {
const onComplete = (response) => {
if (response) {
const grades = {};
this.state.courses.map((course) => {
this.state.studentDetails.map((student) => {
response.body.map((grade) => {
// Not sure this will work after you receive multiple details.
// Probably it will require some changes
grades[`${student.id}_${course.id}_${grade.gradeType}`] = grade.grade;
});
});
});
this.setState({grades: grades});
}
}
// Get IDs of students you need to fetch detail for.
const studentIds = this.state.studentDetails.map(student => student.id);
// Fetch details for all students.
// You have to implement endoint that responds with multiple students details if requested.
// E.g:
// Single detail /users/1/grades
// Multiple details /users/1,2,3/grades
request.get(`http://localhost:8080/user/${studentIds.join(',')}/grades`).then(onComplete);
}
答案 1 :(得分:0)
你可以使用async-waterfall
将两个活动都写成一个给其他人提供参数的函数, 在您的情况下,如果有响应,则设置数组并将其传递给您设置状态的下一个函数