2017-01-23 68 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

相關問題