如何使ASync功能等待,直到收集到所有信息?

时间:2017-01-23 12:37:11

标签: javascript node.js reactjs asynchronous

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});。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

你需要按相反的顺序进行。

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

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

答案 1 :(得分:0)

你可以使用async-waterfall

将两个活动都写成一个给其他人提供参数的函数, 在您的情况下,如果有响应,则设置数组并将其传递给您设置状态的下一个函数

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