title: Implementing exponential backoff with Node.js and Promises
body: <p>I'm making about 70 requests to an API in my code. I'm getting an error response telling me that I'm making requests too quickly one after the other and I have decided to use the idea of exponential backoff to get through this problem. </p>
  
  <p>Currently, this is what my code looks like:</p>
  
  <pre><code>  let backoffTime = 1;
  
    for (let i = 0; i &lt; fileIds.length; i++) {
      let fileId = fileIds[i];
      getFileName(fileId, auth)
      .then((name) =&gt; {
        // do some work
      })
      .catch((err) =&gt; {
        // assumes that the error is "request made too soon"
        backoff(backoffTime);
        backoffTime *= 2;
        i--;
        console.log(err);
      });
    }
  
  function backoff(time) {
    let milliseconds = time * 1000;
    let start = (new Date()).getTime();
    while (((new Date()).getTime() - start) &lt; milliseconds) {
      // do nothing
    }
  }
  </code></pre>
  
  <p>My <code>getFileName</code> function makes the request to the API and returns a Promise.</p>
  
  <p>Currently this does not work because Promises are async (kinda). My for loop runs really fast and calls the getFileName function which makes those API requests really fast. Then, it gets the error for some of the API calls in which case it updates the backoffTime. This implementation doesn't work. </p>
  
  <p>Any idea how I can implement this correctly?</p>