我对JavaScript中的Promises很陌生。我试图调用API以使用数组中的日历ID获取日历事件。我通过在map函数中调用API并尝试将生成的对象作为数组来实现。但是结果只是一个未定义对象的数组。
在我的Google搜索中,Promises.all()
应该在异步方法完成时运行。为什么results
未定义?
PS:我进行了调试,可以看到calendarObj
正在正确地从API调用中加载,但是results
仍未定义。
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
}