Here is the function that creates the array:
//retrieve calendar id's
function getCalendarId(){
gapi.client.load('calendar', 'v3', function() {
var request = gapi.client.calendar.calendarList.list();
request.execute(function(resp) {
var calendarID = [];
for (var i = 0; i < resp.items.length; i++) {
var ID = resp.items[i].id;
var calendarSummary = resp.items[i].summary;
var calendarLocation = resp.items[i].location;
var calendarDescription = resp.items[i].description;
if (calendarDescription && calendarDescription.indexOf("Resource Tracker") != -1) {
var index = calendarID.length;
calendarID[index] = ID;
}//endif
}//end for
console.log(typeof calendarID);
return calendarID;
});//end request.execute function(resp)
});//end client.load function
}//end getCalendarId
And here is the function that assigns it:
function submitEvents(numHorses){
var startdate = $("#from").val();
var enddate = $("#to").val();
var horsetypes = [];
var calid = [];
console.log(typeof(calid));
calid = getCalendarId();
console.log(typeof(calid));
for (i=0; i<numHorses;i++){
horsetypes[i] = $( "#type"+i).val();
addEvent(calid[i%calid.length], startdate, enddate, horsetypes[i]);
}//end for
};//end submitEvents
When I check the type, calendarID is an object just before being returned, and calid is an object when I declare it, but when I make the assignment calid=getCalendarID(); the type of calid becomes undefined.
I’ve been banging my head against the wall for a while now; any help is appreciated!
Nothing returns from the outermost function; it has no return value, so the variable set to the return value of the function is set to undefined. The inner anonymous function contains the
return, which may or may not have meaning to the API (probably not).The real problem is that the call to the calendar API might take an arbitrary amount of time (it’s asynchronous), so you can’t set the value within a single (synchronous) function and expect it to work. Javascript will not stop executing while your request makes its way to and from remote servers, and you really don’t want it to.
Since you may be using
getCalendarIdother places, you could consider having it take a function of its own, and call that when the Google Calendar function returns: