I'm quite new to Promises in JavaScript. I'm attempting to call an API to get calendar events using calendar IDs in an array. I do this by calling the API in a map function and attempt to put the resulting object as an array. However the result is simply an array of undefined objects.
From my Googling, Promises.all()
should run when an async method completes. Why then are the results
undefined?
PS: I debugged and can see the calendarObj
is getting loaded from the API call correctly, however results
is still undefined.
async function getCalendarEvents(calendarList) {
if (debug) {
console.log("searching between " + this.query.timeMin + " and " + this.query.timeMax);
}
var calendars = [];
// Loop through all calendars and extract events
const results = calendarList.map(async (calendar, i) => {
if (calendar.summary != "Holidays in United Kingdom") {
this.client.events.list({
calendarId: calendar.id,
timeMin: this.query.timeMin,
timeMax: this.query.timeMax,
maxResults: this.query.maxResults,
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) {
if (debug) // true
console.log("Loading " + events.length + " events for " + calendar.summary);
var calendarObj = {
name: calendar.summary,
id: calendar.id,
events: events
};
// calendars.push(calendarObj);
return calendarObj;
} else {
if (debug)
console.log('No upcoming events found for ' + calendar.summary);
}
});
}
});
Promise.all(results).then((completed) => console.log(completed)); // returns an array of undefined
}