I'm writing Javascript in a client-only environment, calling an API of a service that is rate-limited. My environment only lets me load JS libraries by using LazyLoad.js which doesn't work for everything. I have successfully been able to use throttled-queue to rate limit my API requests. But I have not been able to combine using that with leveraging Promise.all to check when a series of API calls have been completed. It works if I leave out the throttling, but not with it.
How can I combine these two? The only approach I've come up with so far, which seems very clunky, is to manually rate limit using setTimeout for each call. Then I found I need to wait the total amount of time (e.g. 200ms for each call) before I check Promises.all, otherwise it resolves too quickly with the first few Promises. Here's what I have:
var deferreds = [];
$.each(evalTempQuestions, function(idx, evalTempQuestion){
setTimeout(function(){
deferreds.push(knackAPI('POST', 116, 75, evalTempQuestion.payload));
}, 200 * idx);
});
setTimeout(function(){
Promise.all(deferreds).then(function(r) {
console.log('done');
}).catch(function(err){
console.log(err);
});
}, 200 * evalTempQuestions.length);
How can I do this better?