对API的异步映射函数调用,返回未定义的数组

时间:2018-10-03 13:29:06

标签: javascript asynchronous async-await

我对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
}

控制台输出:enter image description here

0 个答案:

没有答案