2017-01-23 48 views
1
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});只有在收集所有信息时才被调用。我怎样才能做到这一点?如何使一个ASync函数等待,直到收集到所有信息?

回答

1

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

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

UR答案是真棒,只是想知道他是打所有的学生一个接一个地图功能里面的API,但在乌拉圭回合的情况下这将如何工作的? –

+0

'多个细节/ users/1,2,3/grades'我不能这样称呼api,我真的必须一个接一个地做。 – Drago

相关问题