1

I'm trying to retrieve a list of events from a google calendar and that works but I can't figure how to save them in a struct. The struct is empty at the last log but logs "2" directly after pushing the values. I know it's scope Issue, but I can't find a solution.

I would really appreciate if someone has a Tip or a solution for me. Thank you in advance.

// Get all the events between two dates
const getEvents = async (dateTimeStart, dateTimeEnd) => {

    try {
        let response = await calendar.events.list({
            auth: auth,
            calendarId: calendarId,
            timeMin: dateTimeStart,
            timeMax: dateTimeEnd,
            timeZone: 'Europe/Berlin'
        });
    
        let items = response['data']['items'];
        return items;
    } catch (error) {
        console.log(`Error at getEvents --> ${error}`);
        return 0;
    }
};

let start = '2021-12-01T00:00:00.000Z';
let end = '2022-01-01T00:00:00.000Z';

var Events = {
    date: new Array(),
    title: new Array()
}; 

var test = getEvents(start, end)
    .then((res) => {
        for(let i = 0; i < res.length; i++)
        {
            let DateGFormat = '';

            // Filter Full Day Events and Timed Events
            if(res[i].start.dateTime)
            {
                DateGFormat = res[i].start.dateTime.split('T')[0];
            }
            else 
            {
                DateGFormat = res[i].start.date;
            }

            let Year = DateGFormat.split('-')[0];
            let Month = DateGFormat.split('-')[1];
            let Day = DateGFormat.split('-')[2];

            const dayString = `${Day}/${Month}/${Year}`;
            const Title = res[i].summary;

            Events.date.push(dayString);
            Events.title.push(Title);
            console.log(Events.date.length);
        }
    })
    .catch((err) => {
        console.log(err);
    });

console.log(Events.date.length);

1 Answers1

0

Your last console gets called immediately after getEvents gets called. It doesn’t wait until getEvents is resolved. That’s why the console comes back blank.

If you call getEvents using await instead then your program will wait for getEvents to finish before it calls the last console.

Craig Gehring
  • 3,067
  • 1
  • 9
  • 11