Search code examples
javascripttimeoutsettimeoutfetch-api

Setting a delay in fetch API call


I am looping through an array of id and calling an API each time with the id.
The code works but the issue is the result obtained is not consistent in each loop. In some of the loop the response is "You have reached the maximum per-second rate limit".
So I added a delay of 3 seconds to the fetch function but it doesn't seem to work.

Code:

export async function getThirdAPI(access_token, id_array, globalObject) {
  
 const apiPromises = id_array.map(async (id) => {
   return new Promise(resolve => setTimeout(resolve, 3000)).then(async()=>{
    let url = `${baseAPI}/participants/${id}`;
    var obj = {
      method: 'GET',
      headers: {  
      authorization: `Bearer ${access_token}`
         }
    }
    const response = await fetch(url, obj);
    return await response.json();
    })
  });

  const results = await Promise.all(apiPromises);
  console.log(results)

  globalObject.store_data.push(...results);

  return globalObject;
}

When I console log "results" I get something like below:

{
  page_count: 1,
  page_size: 300,
  total_records: 2,
  next_page_token: '',
  participants:[ Object }
},
{
  page_count: 1,
  page_size: 300,
  total_records: 3,
  next_page_token: '',
  participants:[ Object }
},
{
  code: 429,
  message: "You have reached the maximum per-second rate limit. Try again later"
},
{
  page_count: 1,
  page_size: 300,
  total_records: 11,
  next_page_token: '',
  participants:[ Object }
},
{
  code: 429,
  message: "You have reached the maximum per-second rate limit. Try again later"
}

Any suggestions would be great!


Solution

  • A little hacky solution is to preschedule all the promises with an incrementing delay. First after 500ms, second after 1000ms, third after 1500ms etc.

    var delay = 1000;
    
    const apiPromises = id_array.map(async(id, index) => {
      return new Promise(resolve => setTimeout(resolve, delay * index)).then(async() => {
        let url = `${baseAPI}/participants/${id}`;
        var obj = {
          method: 'GET',
          headers: {
            authorization: `Bearer ${access_token}`
          }
        }
        const response = await fetch(url, obj);
        return await response.json();
      })
    });