[英]Google Calendar javascript api - Add multiple events
當我嘗試通過javascript v3 api將多個事件添加到Google日歷時遇到了一個問題。
我有一個數組,條目是這樣的事件:
newEvent = { "summary": response[i].name+" BDay!!", "start": { "dateTime": date }, "end": { "dateTime": date } }; events[i]=newEvent;
之后,我打電話給Google Calendar API以添加事件:
var request;
for(var j = 0; j<events.length; j++) {
console.log(events[j]);
request = gapi.client.calendar.events.insert({
'calendarId': calendarId,
'resource': events[j]
});
request.execute(function(resp) {
console.log(resp);
});
}
但是,事實證明,所有事件都放在日歷的同一日期(實際上是數組events []中的最后一個日期)。 我相信可能是因為請求是回調函數,但我不確定。
希望能有所幫助!
如果要一次插入多個事件,則應使用批處理。
var batch = gapi.client.newBatch();
batch.add(gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': events[0]
}));
batch.add(gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': events[1]
}));
batch.add(gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': events[2]
}));
......
batch.then(function(){
console.log('all jobs done!!!')
});
在for循環的每次迭代中, events[j]
都會反彈。 嘗試使用匿名函數綁定到正確的事件:
var request;
for(var j = 0; j<events.length; j++) {
console.log(events[j]);
request = function(resource) { // Function that returns a request.
return gapi.client.calendar.events.insert({
'calendarId': calendarId,
'resource': resource
});
}(events[j]); // Bind to the current event.
request.execute(function(resp) {
console.log(resp);
});
}
有關JavaScript數組和閉包的更多詳細信息,請參見以下問題: 循環內的JavaScript閉包–簡單的實際示例
這是上面代碼的易於閱讀的版本,它將所有處理移到一個函數中:
var makeRequest = function(resource) {
console.log(resource);
var request = gapi.client.calendar.events.insert({
'calendarId': calendarId,
'resource': resource
});
request.execute(function(resp) {
console.log(resp);
});
};
for(var j = 0; j<events.length; j++) {
makeRequest(events[j]);
}
作為提及,您需要使用批處理來添加多個事件
為什么要批處理? 使用批處理API的主要原因是為了減少網絡開銷,從而提高性能。
例:
createMultipleEvents() {
const events = [ {
'summary': 'sample test events1',
'location': 'coimbatore',
'start': {
'date': '2018-08-29',
'timeZone': 'America/Los_Angeles'
},
'end': {
'date': '2018-08-29',
'timeZone': 'America/Los_Angeles'
}
},
{
'summary': 'sample test events2',
'location': 'coimbatore',
'start': {
'date': '2018-08-29',
'timeZone': 'America/Los_Angeles'
},
'end': {
'date': '2018-08-29',
'timeZone': 'America/Los_Angeles'
}
},
];
const batch = gapi.client.newBatch();
events.map((r, j) => {
batch.add(gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': events[j]
}))
})
batch.then(function(){
console.log('all jobs now dynamically done!!!')
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.