1

I have a function that takes, as an argument, the response from the gapi.client.calendar.events.list call on the Google Calendar API.

I'm trying to iterate through that response, and .push() the elements to an array (localEventList). When I check the value of localEventList immediately after the for-loop, the events are stored in it, but when I check it outside of .execute(function(events){... function, the array is still empty. I've tried initializing the array to different values, and the array remains at the value it is initialized to.

I don't understand why the variable isn't staying mutated, since it's initialized in the overarching function call. Also, I'm not really clear on the purpose of the .execute(... call.

If anyone could clarify either of these two issues, I'd love you forever.

function parseEvents(calEventRequest){
var localEventList = new Array();

calEventRequest.execute(function(events){
    for(i = 0; i < events.items.length; i++){
        var item = events.items[i];
        var name = item.summary;
        var start = item.dateTime;
        localEventList.push(name);
    };
    // If I place a console.log(localEventList) here, the array is populated
}); 
console.log(localEventList); // But the call here displays an empty array. 
}
David Cai
  • 31
  • 4
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Phil May 30 '16 at 03:36

1 Answers1

1

The simple answer to your question is console.log() will not wait for the calEventRequest.execute() function to be completed, if you are working with angularJs or any other js framework you can handle this operation with defer and promise like features which will wait for the api call and return the response only after finish.

the solution to your problem is to use a callback function after the forloop as below

// calling the parseEvents function 
parseEvents(calEventRequest,function(eventList){
console.log(eventList);
//this will print the array after for loop finished
})

function parseEvents(calEventRequest,callback){
var localEventList = new Array();

calEventRequest.execute(function(events){
    for(i = 0; i < events.items.length; i++){
        var item = events.items[i];
        var name = item.summary;
        var start = item.dateTime;
        localEventList.push(name);
    };
    if(callback)callback(localEventList);
    // If I place a console.log(localEventList) here, the array is populated
}); 
console.log(localEventList); // But the call here displays an empty array. 
}
rashidnk
  • 4,096
  • 2
  • 22
  • 32
  • Thanks! It was the callback issue that got me. If anyone wanted to know even more, I found this thread helpful: [link](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – David Cai May 30 '16 at 21:52
  • glad to know it helped u :) – rashidnk May 31 '16 at 03:49