Javascript 使用Goggle课堂API的课程及其学生列表

Javascript 使用Goggle课堂API的课程及其学生列表,javascript,google-api,google-classroom,Javascript,Google Api,Google Classroom,我是新使用谷歌课堂API的人,我正试图得到一份课程和学生的列表,如下所示: 课程1: 学生: 学生1.1 学生1.2 学生1.3 课程2: 学生: 学生2.1 学生2.2 学生2.3 学生2.4 但我的代码是: 课程1: 课程2: 学生: 学生1.1 学生1.2 学生1.3 学生: 学生2.1 学生2.2 学生2.3 学生2.4 你知道为什么吗 function listCourses() { gapi.client.classroom.courses.list({

我是新使用谷歌课堂API的人,我正试图得到一份课程和学生的列表,如下所示:

课程1:

学生: 学生1.1 学生1.2 学生1.3

课程2:

学生: 学生2.1 学生2.2 学生2.3 学生2.4

但我的代码是:

课程1: 课程2:

学生: 学生1.1 学生1.2 学生1.3

学生: 学生2.1 学生2.2 学生2.3 学生2.4

你知道为什么吗

    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.');
        }
      });
    }
函数列表课程(){
gapi.client.教室.courses.list({
页面大小:10,
}).然后(功能(响应){
var课程=response.result.courses;
附录(课程名称:);
如果(课程长度>0){
对于(i=0;i0){
对于(i=0;i
因为对
gapi.client.教室.courses.list
教室.courses.students.list
端点的调用都是异步的,所以您最终会从您的courses.list请求中得到响应,然后迭代检索到的每个课程。但是,在您的
for
循环中,您发送了列出给定课程的学生的请求,但没有等待响应,因此创建了承诺,但是您的for循环在继续处理下一个课程之前没有等待响应

本质上,您需要考虑
中的所有内容。然后(
作为一个单独的进程运行,最终将运行,但不会阻止代码执行。调用
gapi.client
返回的对象返回一个,可以像任何其他承诺一样处理

根据您正在构建的环境,您可能希望使用
async await
()或Promise库()以阻塞方式处理这些异步代码块

您还需要确保您正在处理students端点上的分页,因为类最多可以有1000个学生,并且您可能会遇到包含多个结果页面的类