【问题标题】:Showing all Events from multiple Google Calendars显示来自多个 Google 日历的所有事件
【发布时间】:2018-02-10 18:28:13
【问题描述】:

我有多个谷歌日历,我想使用 javascript 上的谷歌日历 api 将它们显示在一个列表中(比如在谷歌日历 UI 上)。

official google calendar api doc 很不错。主要截图如下:

function listUpcomingEvents() {
    gapi.client.calendar.events.list({
      'calendarId': 'primary',
      'timeMin': (new Date()).toISOString(),
      'showDeleted': false,
      'singleEvents': true,
      'maxResults': 10,
      'orderBy': 'startTime'
    }).then(function(response) {
      var events = response.result.items;
      appendPre('Upcoming events:');

      if (events.length > 0) {
        for (i = 0; i < events.length; i++) {
          var event = events[i];
          var when = event.start.dateTime;
          if (!when) {
            when = event.start.date;
          }
          appendPre(event.summary + ' (' + when + ')')
        }
      } else {
        appendPre('No upcoming events found.');
      }
    });
  }

由于我有多个日历,我显然必须用我的多个日历 ID 替换 'calendarId': 'primary' 请求。要获得各种 id 也很简单。例如:

function listCalendars() {
    gapi.client.calendar.calendarList.list({

    }).then(function(response) {
      var calendars = response.result.items;
      console.log(calendars);
    });
  }

由于提到的'calendarId': 'primary' 只接受一个值(而不是列表),我必须多次调用端点gapi.client.calendar.events.list 才能获取所有事件。

但是当我想按顺序安排我的活动时(由于它是日历而使用开始日期),我必须对它们进行排序。

因为它是异步的,我不确定如何收集所有事件然后对其进行排序。任何想法如何做到这一点? (或同时请求多个日历中的所有事件/调用?)

【问题讨论】:

    标签: javascript google-calendar-api


    【解决方案1】:

    我想到你可以使用的一件事是Promises

    可能的解决方案是:

    function callAllCalendars() {
       var promises = []
       var calendarIdList = ["calendar1", "calendar2", "calendar3"];
       for(var i = 0; i < calendarIdList .length, i++){
          promises.push(createCalendarPromise(calendarIdList [i]));
       }
       $.when.apply($, promises).done(function () {
          ... Your code to do the sorting ...
       });
    
    }
    
    function createCalendarPromise(calendarId) {
       var dfd = $.Deferred();
       gapi.client.calendar.events.list({
            'calendarId': calendarId,
             ... Your code...
       }).then(function(response) {
          ... Your Code, push events to a global list...
          dfd.resolve();
      }).fail(function() { dfd.resolve();});
    
      return dfd.promise
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 2014-10-23
      • 2014-05-17
      • 2020-07-14
      • 2023-03-22
      相关资源
      最近更新 更多