title: Node, wait and retry api calls that fail
body: <p>So I <code>fetch</code> an array of urls from api with a rate limit, currently I handle this by adding a timeout to each call like this:</p>
  
  <pre><code>const calls = urls.map((url, i) =&gt;
    new Promise(resolve =&gt; setTimeout(resolve, 250 * i))
      .then(() =&gt; fetch(url)
    )
  );
  
  const data = await Promise.all(calls);
  </code></pre>
  
  <p>forcing a 250ms wait between each call. This ensures that the rate limit is never exceeded.</p>
  
  <hr>
  
  <p>The thing is, this isn't really necessary. I've tried with 0ms wait time, and most of the cases I have to repeatedly reload the page four or five times before the api starts to return:</p>
  
  <p><code>{ error: { status: 429, message: 'API rate limit exceeded' } }</code></p>
  
  <p>and most of the times you only have to wait a second or so before you can safely reload the page and get all data.</p>
  
  <p>A more reasonable approach would be to collect the calls that return 429 (if they do), wait for a set amount of time and then retry them (and perhaps redo this a set amount of times).</p>
  
  <p>Problem, I'm a bit stumped as to how one would go about achieving this?</p>
  
  <p>EDIT:<br>
  Just got home and will look through the answers but there seem to have been an assumption made which I don't believe is necessary: The calls does not have to be <strong>sequential</strong>, they can be fired (and returned) in any order.</p>