2

I need to make some consecutive calls to an API until the request limit completes. After each request, something is saved to the db and the next request depends on the values retrieved from the first request, so every request can't be started until the previous one finishes.

A common while loop won't work because it will run all the promises in a parallel way. And promises concatenated after each other will only work for a fixed number of requests.

So, how to do achieve a promises while loop?

Basically what I want:

let remaining = 200;
let start_id = null;

while (remaining > 0) {
  // make http request with param start_id
  // save results to db
  // update 'update' start_id
  // update 'remaining' from http header
}
Mathius17
  • 2,412
  • 2
  • 21
  • 33

1 Answers1

3

I was thinking of something like (pseudo code):

function makeAsyncCall(data) {
    if (data) {
        // save to db
    }
    $.ajax({
        url: '/url',
        success: function(data) {
           makeAsyncCall(data);
        }
    })
}

And then you need to have a flag to decide when to stop to call the function.

Jonas Grumann
  • 10,438
  • 2
  • 22
  • 40
  • A recursive function? I'll try it, thanks! – Mathius17 Sep 05 '16 at 14:44
  • No promises, no error handling :-( – Bergi Sep 05 '16 at 14:55
  • You're right about the promises. No error handling because I wanted to show only the core of what is relevant to the question. What exactly is the problem of using this without promises? – Jonas Grumann Sep 05 '16 at 14:59
  • JavaScript does not have tail-optimisation for recursion, what means that it could potentially blow the stack. I would avoid using recursion in JavaScript. – edufinn May 18 '17 at 06:49