Lexander Lexander - 2 months ago 21
Javascript Question

How to check if google calendar api request has finished?

This is a part of the official Google calendar api example. This code executes asynchronously, which means that if I put a function using received data below, it starts before it gets results needed. How to ensure that the request has finished its job and results are ready? Thanks

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

request.execute(function(resp) {
var events = resp.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.');
}

});
}

Answer

Create your own function

myEvents(events){
  // console.log(events);
}

Call it in the request callback

The anonymous function here is the Google Calendar request callback. So when the request has finished, this function is executed.

function listUpcomingEvents() {

  [...]

  // Google calendar API request
  request.execute(function(resp) {
    // Google calendar API request has finished
    var events = resp.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.');
    }

    // Here, you're function call
    myEvents(events)

  });
}
Comments