我有一个功能createEvent()
向Google日历发送请求。
Google Calendar的API要求我每秒最多发送5个请求。
如果我拨打createEvent()
100次,它将会激活谷歌日历,我的请求将被拒绝。如果可能的话,我希望createEvent()
包含将请求限制为每秒5次所需的逻辑。
我试图避免,
calendar.addEventToQueue(eventData);
calendar.addEventToQueue(eventData);
calendar.addEventToQueue(eventData);
cleandar.submitEvents();
而只是
calendar.createEvent(eventData);
calendar.createEvent(eventData);
calendar.createEvent(eventData);
答案 0 :(得分:1)
我想我早在rate limiting给出了这个答案。
您可以使用RxJS:
//This would be replaced by whatever your event source was
//I just made it a button click in this case
var source = Rx.Observable.fromEvent($button, 'click')
//Captures either all the events for one second for a max of 5 events
//Projects each set into an Observable
.windowWithTimeOrCount(1000, 5)
//Only the first window in a single second gets propagated
//The others will be dropped
.throttleFirst(1000)
//Flatten the sequence by concatenating all the windows
.concatAll()
//Build the event body now *after* we have done filtering
.flatMap(function() {
//The calendar request api supports promises which are
//handled implicitly in Rx by operators like flatMap. As a result
//this will automatically wait until it receives a response.
return gapi.client.calendar.events.insert(/*event body*/);
});
//Process the response
source.subscribe(
function(response) { console.log('Event successfully created!'); });