I have a var gehad
that calls a function that takes all events from a google Calendar and pushes them into an array named "test". The test array is then returned to the var gehad
, But it always returns an array without length
.
Also inside the loop where I push events into the test Array, I can console.log(test[0].id)
and it will return
the id. but if I console.log
the same thing outside the loop. it returns an Uncaught TypeError
I am so confused as to why it does that.
my code:
var gehad = listUpcomingEvents();
console.log(gehad); //<!-- output:[0]{kind: "calendar#event, id: "10010", status: "confirmed", …} length:1 __proto__: Array(0)
console.log('gehad.length: ' + gehad.length); //<!-- output: 0; expected output: 1
console.log(gehad[0]);//<!-- output: undefined
function listUpcomingEvents() {
//Creates a list of all events on the google Calendar
var test = [];
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
}).then(function (response) {
var events = response.result.items;
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
test.push(events[i]);
console.log(test[0].id) //<!-- returns a valid id
}
}
});
console.log(test[0].id) //<!-- Uncaught TypeError: Cannot read property 'id' of undefined
return test;
}
Thank you.
(yes there are events on my google calendar)