title: Make an async function execution wait after the 4th call
body: <p>I am using fetch to make API calls to a 3rd party API. I have multiple access tokens to help prevent me from reaching their rate limit. The problem I am having is that the loop isn't working properly. After the initial loop, only the 2nd key in the array is called and therefore hits the API limit.</p>
  <p>Here is the code:</p>
  <pre><code>// outside of function scope for keeping track of which key to use
  let count = -1;
  
  export default async function apiCall(
    request_type: string,
    url: string,
    request_body?: RequestInit,
    headers?: HeadersInit
  ) {
    const keys: string[] = [
      `${env.API_KEY_0}`,
      `${env.API_KEY_1}`,
      `${env.API_KEY_2}`,
      `${env.API_KEY_3}`,
    ];
  
    if (count === 4) {
      await wait(5);
      count = 0;
    }
  
    const request: RequestInit = {
      method: request_type,
      headers: headers
        ? headers
        : {
            &quot;Content-Type&quot;: &quot;application/json&quot;,
            &quot;Access-Token&quot;: `${keys[count]}`,
          },
    };
  
    if (request_type !== &quot;GET&quot; &amp;&amp; request_type !== &quot;DELETE&quot;) {
      request.body = JSON.stringify(request_body);
    }
  
    // used to switch the tokens to prevent rate_limiting. Faster than using a rate limiter in each function
    count++;
  
    console.log(keys[count]);
    // return await fetch(`https://api.com/${url}`, request)
    //   .then((result) =&gt; {
    //     return result.json();
    //   })
    //   .catch((error) =&gt; {
    //     console.log(error);
    //   });
  }
  
  const wait = (seconds = 1) =&gt; {
    new Promise((r) =&gt; setTimeout(r, seconds * 1e3));
  };
  </code></pre>
  <p>And here is the console output showing me it's not waiting after the 4th function call:</p>
  <pre><code>API_KEY_1
  API_KEY_2
  API_KEY_3
  undefined
  API_KEY_1
  API_KEY_1
  API_KEY_1
  API_KEY_1
  API_KEY_1
  ...
  </code></pre>
  <p><strong>EDIT</strong></p>
  <p>Part of the problem was the wait function not returning, but even after the wait function call is done, it doesn't reset properly as shown in the console.log here:</p>
  <pre><code>API_KEY_1
  API_KEY_2
  API_KEY_3
  undefined
  Waiting...
  API_KEY_1
  API_KEY_1
  API_KEY_1
  API_KEY_1
  API_KEY_1
  ...
  </code></pre>
  <p>Here's a playground that will give better insight to what I am seeing: <a href="https://playcode.io/968433" rel="nofollow noreferrer">https://playcode.io/968433</a></p>
  <p>The desired outcome is:</p>
  <pre><code>API_KEY_1
  API_KEY_2
  API_KEY_3
  API_KEY_4
  Waiting...
  API_KEY_1
  API_KEY_2
  API_KEY_3
  API_KEY_4
  Waiting...
  ...
  </code></pre>