I'm struggling with handling a call to the Google Calendar API. I've slightly modified the Node.js quickstart from the Google API docs for my needs. I'm trying to retrieve all events from the calendar but when I try to await the return, all I get is Promise { <pending> }
. Is there a better way to wait for the call or is there something I'm totally missing?
async function listEvents() {
const calendar = google.calendar({version: 'v3', auth: apiKey});
return await calendar.events.list({
calendarId: <calendarID>,
timeMin: oneWeekAgo,
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const events = res.data.items;
if (events.length) {
events.forEach(el => console.log(el.summary))
// console.log(events)
// eventList = events
return events
} else {
console.log('No upcoming events found.');
}
});
}
FWIW, the events do eventually log to the console, I just can't figure out how to get the function to wait for that promise to resolve before returning.
You are trying to use await with a callback style. I guess if you just remove the callback function and put await it will return you the details
async function listEvents() {
const calendar = google.calendar({version: 'v3', auth: apiKey});
const res = await calendar.events.list({
calendarId: <calendarID>,
timeMin: oneWeekAgo,
maxResults: 10,
singleEvents: true,
orderBy: 'startTime',
});
const events = res.data.items;
if (events.length) {
events.forEach(el => console.log(el.summary))
// console.log(events)
// eventList = events
return events
} else {
console.log('No upcoming events found.');
}
}