juantoman
juantoman

Reputation: 11

List of courses and their students using Goggle Classroom API

I'm new using Google Classroom API and I'mtrying to get a list of courses and their students like that:

Course 1:

students: Student 1.1 Student 1.2 Student 1.3

Course 2:

students: Student 2.1 Student 2.2 Student 2.3 Student 2.4

...

But my code gets:

Course 1: Course 2:

students: Student 1.1 Student 1.2 Student 1.3

students: Student 2.1 Student 2.2 Student 2.3 Student 2.4

Do you know why?

    function listCourses() {
      gapi.client.classroom.courses.list({
        pageSize: 10,
      }).then(function(response) {
        var courses = response.result.courses;
        appendPre('Courses:');
        if (courses.length > 0) {
          for (i = 0; i < courses.length; i++) {
            var course = courses[i];
            appendPre(course.name+":"+course.id)
            listStudents(course.id);
          }
        } else {
          appendPre('No courses found.');
        }
      });
    }

    function listStudents(c) {
      gapi.client.classroom.courses.students.list({
        courseId: c
      }).then(function(response) {
        console.log(response.result);
        var students = response.result.students;
        appendPre('students:');
        if (students.length > 0) {
          for (i = 0; i < students.length; i++) {
            var student = students[i];
            appendPre(c+":"+student.userId+":"+student.profile.name.fullName)
          }
        } else {
          appendPre('No students found.');
        }
      });
    }

Upvotes: 1

Views: 1918

Answers (1)

James
James

Reputation: 96

Because both the calls to the gapi.client.classroom.courses.list and the classroom.courses.students.list endpoints are asynchronous, you're ending up getting the response from your courses.list request, then iterating through each course retrieved. However, inside your for loop, you're sending the request to list the students for the given course, but not waiting for the response, so the promise gets created, but your for loop is not waiting for the response before moving on to process the next course.

Essentially, you need to think of everything inside your .then( function as a separate process that will eventually run, but won't block your code execution. The return object from your calls to gapi.client return a goog.Thenable, which can be handled as any other promise would.

Depending on the environment in which you're building, you'll want to either look at using async await (read about it here) or a Promise library (I like bluebird) to handle these asynchronous code blocks in a blocking manner.

You'll also need to ensure that you're handling paging on the students endpoint, as classes can have up to 1000 students, and you'll likely run into classes that have more than one page of results.

Upvotes: 1

Related Questions