0

So I have an array of promises, which are returned from an http request. I want to throttle it to around 5 max at a time because the API can't handle too many requests at once. Is the best way to throttle the promises or to throttle the requests? The code is complicated but basically boils down to this:

var requests = [promise1, promise2...];
$q.all(requests);

Any ideas?

Jack Johnson
  • 1,327
  • 3
  • 12
  • 18
  • Related (at least): https://stackoverflow.com/questions/20546373/how-can-i-limit-q-promise-concurrency – T.J. Crowder Jan 23 '20 at 16:13
  • Note that if you're receiving promises, the processes they represent have *already been started* and there's nothing you can do to limit them. You have to get involved earlier, before the processes get started. Promises just let you observe the results, they don't actually do the work. – T.J. Crowder Jan 23 '20 at 16:14
  • *"So I have an array of promises, which are returned from an http request."* How would an HTTP request return *promises*? – T.J. Crowder Jan 23 '20 at 16:15
  • Thanks for that link, I'll see if it works for my situation. As for your last question, the $http service from AngularJS returns promises I believe. – Jack Johnson Jan 23 '20 at 16:20
  • The `$http` service's methods return **a** promise you can use to observe that request, yes. That's not how I read *"an array of promises, which are returned from an http request."* I think the shift from plural to singular threw me. So what you need to do is get involved *before* those `$http` service calls are made. – T.J. Crowder Jan 23 '20 at 16:22
  • Yes my apologies on the verbage. I think when I push the $http service calls onto the array, the calls aren't made until I call the .all. I have tested this and that's the behavior I was seeing. – Jack Johnson Jan 23 '20 at 16:38
  • No, that's incorrect. `$q.all` (like `Promise.all`) doesn't *start* anything. It just observes the results. By the time you're calling `$q.all`, the HTTP request calls have already been started. (If you're stepping through in the debugger, that may not be obvious, but that's how it works.) This is a **key** thing about promises. – T.J. Crowder Jan 23 '20 at 16:42
  • 1
    Ah ok thanks, I guess I just need to figure out how to throttle the actual http calls then – Jack Johnson Jan 23 '20 at 17:17

0 Answers0