简体   繁体   中英

How do I make an ASync function wait, till all the information is gathered?

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

I want that this.setState({grades: grades}); is only called when if all the information is gathered. How can I do this?

You need to do it in opposite order.

  1. fetch data
  2. set state

-

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

you may use async-waterfall

write both activity as a function one giving parameter to other , in your case set the array if there is a responce and pass it to the next function where you set the state

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM