【问题标题】:How do I make an ASync function wait, till all the information is gathered?如何让异步函数等待,直到收集到所有信息?
【发布时间】:2017-06-07 23:26:16
【问题描述】:
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});。我该怎么做?

【问题讨论】:

    标签: javascript node.js reactjs asynchronous


    【解决方案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);
    }
    

    【讨论】:

    • 你的回答太棒了,只是想知道他在地图功能中为所有学生一一点击了 api,但在你的情况下,这将如何工作?
    • Multiple details /users/1,2,3/grades 不能这样调用api,真的要一个一个来做。
    【解决方案2】:

    你可以使用异步瀑布

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

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

    【讨论】:

      猜你喜欢
      • 2016-10-28
      • 1970-01-01
      • 2021-10-02
      • 2018-08-12
      • 2018-09-29
      • 2014-06-28
      • 2022-01-27
      • 2021-04-16
      相关资源
      最近更新 更多