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

ウル答えは驚くばかりである状態を設定したイオンは、ちょうど彼がmap関数内の一つ、すべての学生の1のためのAPIに当たっている知りたいが、ウル場合には、これは動作しますか? –

+0

'複数の詳細/ユーザー/ 1,2,3 /等級'私はそのようなAPIを呼び出すことはできません、私は本当にそれを一つずつ行う必要があります。 – Drago

0

あなたは

が 、他にパラメータを与える機能として両方の活動を書き非同期滝を使用することができますあなたのケースでは、応答がある場合は配列を設定し、次の関数に渡しますあなたは

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

関連する問題