Используя node.js и graphql - я пытаюсь отобразить общее количество учеников в каждой школе, но в Promise.all () он возвращает пустое значение. - PullRequest
0 голосов
/ 12 марта 2020
    async studentCount(@Parent() school: School): Promise<number> {
        let studentIds = []
        let cohortStudentIds = []

        // find all the programs for each school
        const programs = await this.programService.find({ schoolId: school.id })

        // find all the cohorts for each program
        programs.map(async program => {

//collect the student ids per cohort within array
          const cohortsWithStudents = await this.cohortService.getStudentsForCohortsByProgramId(program.id)
          // find all the students by looping through each cohort and save in cohortStudentIds[]
          cohortsWithStudents.map(async (cohort) => {
            await cohort.students.map(async (student) => { await cohortStudentIds.push(student.id) })

          });
//collect all the student id arrays into 1 big array
        studentIds = await [
            ...studentIds,
            ...cohortStudentIds
          ]

        })

        await Promise.all([programs, cohortStudentIds, studentIds])
            .then((values) => {
              console.log( values )
              return values
            });
            console.log('xxx')

        //  return the number of students per school
        return uniq(studentIds).length
      }

1 Ответ

0 голосов
/ 12 марта 2020

Вы передаете функцию async в качестве обратного вызова для map(), что приводит к массиву обещаний, но вы никогда не ждете этих .

В напротив, вы await получаете много вещей, которые вам не нужно ждать, поскольку они не являются обещаниями, например, возвращаемое значение push, возвращаемое значение map или литерал массива.

Вы должны написать что-то вроде

async studentCount(@Parent() school: School): Promise<number> {
    let studentIds = new Set

    const programs = await this.programService.find({ schoolId: school.id })

    await Promise.all(programs.map(async program => {
//  ^^^^^^^^^^^^^^^^^
        const cohortsWithStudents = await this.cohortService.getStudentsForCohortsByProgramId(program.id)
        for (const cohort of cohortsWithStudents) {
            for (const student of cohort.students) {
                studentIds.add(student.id)
            }
        }
    });

    return studentIds.size
}
...