使用 Google(日历)API 的可变范围问题

Variable scope issues using Google (calendar) API

我有一个函数将 Google 日历 API 上的 gapi.client.calendar.events.list 调用的响应作为参数。

我正在尝试遍历该响应,并将 .push() 元素添加到数组 (localEventList)。当我在 for 循环之后立即检查 localEventList 的值时,事件存储在其中,但是当我在 .execute(function(events){... 函数之外检查它时,数组仍然是空的。我已经尝试将数组初始化为不同的值,并且数组保持在它初始化的值。

我不明白为什么变量没有保持变异状态,因为它是在总体函数调用中初始化的。另外,我不太清楚 .execute(... 调用的目的。

如果有人能澄清这两个问题中的任何一个,我会永远爱你。

function parseEvents(calEventRequest){
var localEventList = new Array();

calEventRequest.execute(function(events){
    for(i = 0; i < events.items.length; i++){
        var item = events.items[i];
        var name = item.summary;
        var start = item.dateTime;
        localEventList.push(name);
    };
    // If I place a console.log(localEventList) here, the array is populated
}); 
console.log(localEventList); // But the call here displays an empty array. 
}

你的问题的简单答案是 console.log() 不会等待 calEventRequest.execute() 函数完成,如果你正在使用 angularJs 或任何其他你可以处理的 js 框架此操作与 deferpromise 类似的功能将等待 api 调用和 return 仅在完成后响应。

您的问题的解决方案是在 forloop 之后使用 callback 函数,如下所示

// calling the parseEvents function 
parseEvents(calEventRequest,function(eventList){
console.log(eventList);
//this will print the array after for loop finished
})

function parseEvents(calEventRequest,callback){
var localEventList = new Array();

calEventRequest.execute(function(events){
    for(i = 0; i < events.items.length; i++){
        var item = events.items[i];
        var name = item.summary;
        var start = item.dateTime;
        localEventList.push(name);
    };
    if(callback)callback(localEventList);
    // If I place a console.log(localEventList) here, the array is populated
}); 
console.log(localEventList); // But the call here displays an empty array. 
}