title: Using setTimeout to pause rest API calls
body: <p>I have an array of IDs and a fix endpoint that I need to call. So I want to foreach the array of IDs and make a corresponding rest API call for each ID. Since I don't want to "flood" the endpoint, I want to wait a second between each call. Also, I'd like to wait for the response before calling endpoint with a new ID.</p>
  
  <p>Here's what I came up with:</p>
  
  <pre><code>// Code goes here
  console.clear();
  
  const url = 'some-domain.com/v1/api/users';
  const ids = [1, 2, 3, 4, 5, 6, 7];
  const serviceMock = (id) =&gt; new Promise((resolve, reject) =&gt; {
  
    console.log('Got request for id ' + id);
    setTimeout(() =&gt; {
  
      resolve(`${url}${id} returned ${ Math.floor((Math.random() * 100) + 1)}`);
    }, 2000);
  });
  
  const main = async() =&gt; {
  
    let index = 0;
    for (let id of ids) {
  
      index++;
      setTimeout(async() =&gt; {
  
        const data = await serviceMock(id);
        console.log(`Done for user ${id}!`);
        console.log(data);
      }, 1000 * index);
    }
  };
  
  main();
  </code></pre>
  
  <p>The <code>setTimeout</code> in serviceMock is used to simulate the rest API call, and the <code>setTimeout</code> in <code>main</code> is used to pause between the calls.</p>
  
  <p>Now, how I would like it to behave is as follows (in console): </p>
  
  <pre><code>Got request for id 1
  Done for user 1!
  some-domain.com/v1/api/users1 returned 77
  Got request for id 2
  Done for user 2!
  some-domain.com/v1/api/users2 returned 75
  Got request for id 3
  Done for user 3!
  some-domain.com/v1/api/users3 returned 26
  Got request for id 4
  Done for user 4!
  some-domain.com/v1/api/users4 returned 44
  Got request for id 5
  Done for user 5!
  some-domain.com/v1/api/users5 returned 79
  Got request for id 6
  Done for user 6!
  some-domain.com/v1/api/users6 returned 52
  Got request for id 7
  Done for user 7!
  some-domain.com/v1/api/users7 returned 34
  </code></pre>
  
  <p>This is what I get:</p>
  
  <pre><code>Got request for id 1
  Got request for id 2
  Got request for id 3
  Done for user 1!
  some-domain.com/v1/api/users1 returned 77
  Got request for id 4
  Done for user 2!
  some-domain.com/v1/api/users2 returned 75
  Got request for id 5
  Done for user 3!
  some-domain.com/v1/api/users3 returned 26
  Got request for id 6
  Done for user 4!
  some-domain.com/v1/api/users4 returned 44
  Got request for id 7
  Done for user 5!
  some-domain.com/v1/api/users5 returned 79
  Done for user 6!
  some-domain.com/v1/api/users6 returned 52
  Done for user 7!
  some-domain.com/v1/api/users7 returned 34
  </code></pre>
  
  <p>Here's a working example: <a href="http://plnkr.co/edit/sNfk8GIfqbhrpql5hQ16?p=preview" rel="nofollow noreferrer">http://plnkr.co/edit/sNfk8GIfqbhrpql5hQ16?p=preview</a></p>
  
  <p>what exactly am I missing here?</p>