gpt4 book ai didi

javascript - 如何让 ASync 函数等待,直到收集完所有信息?

转载 作者:太空宇宙 更新时间:2023-11-04 00:28:39 25 4
gpt4 key购买 nike

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}); 。我怎样才能做到这一点?

最佳答案

您需要按照相反的顺序进行操作。

  1. 获取数据
  2. 设置状态

-

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);
}

关于javascript - 如何让 ASync 函数等待,直到收集完所有信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41806582/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com