如何使一个ASync函数等待,直到收集到所有的信息?

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. // Eg: // Single detail /users/1/grades // Multiple details /users/1,2,3/grades request.get(`http://localhost:8080/user/${studentIds.join(',')}/grades`).then(onComplete); } 

你可以使用asynchronous瀑布

写两个活动作为一个函数给其他参数,在你的情况下设置数组,如果有一个响应,并将其传递给设置状态的下一个函数

https://www.npmjs.com/package/async-waterfall