Home > Net >  Delay when pulling data from API with JS
Delay when pulling data from API with JS

Time:11-29

I'm pulling a JSON file using js. But since I do this with a for loop, the server gives a 429 error. I looked for ways to slow the cycle. but I couldn't find a working solution. I tried setTimeOut, I tried delay fetch. I guess it wasn't true.

           let koordinatlar = [];
              
           for (let konumOlustur = 0; konumOlustur < 10; konumOlustur  ) {
          musteriAdres = encodeURIComponent(yesilListe[0][konumOlustur][5] ' ' yesilListe[0][konumOlustur][6] ' ' yesilListe[0][konumOlustur][7] ' ' yesilListe[0][konumOlustur][8]);
           fetch(`https://api.tomtom.com/search/2/geocode/${musteriAdres}.json?key=APIKEY`)
            .then((response) => response.json())
            .then((data)=> 
              koordinatlar.push(
              [data['results'][0]['position']['lon'],
              data['results'][0]['position']['lat'],
              yesilListe[0][konumOlustur][2] ' ' 
              yesilListe[0][konumOlustur][3],
              yesilListe[0][konumOlustur][4],
              yesilListe[0][konumOlustur][5] ' ' 
              yesilListe[0][konumOlustur][6] ' ' 
              yesilListe[0][konumOlustur][7] ' ' 
              yesilListe[0][konumOlustur][8]]))
            .catch(function(){
            console.log("hata")
            });
          }
          console.log(koordinatlar);
          </script>

CodePudding user response:

You can use a .setTimeout() for a forced delay.

Check the documentation for the API limit, if there isn’t this information try some different values times until it works.

CodePudding user response:

While I can't find any information about rate limits on the developer documentation site, I did find this comment in the support forums:

The Default QPS limit for Search API is set to five.

According to that comment and others in the developer forums, you'll need to throttle your requests to no more than 5 per second (which translates to 1 query every 200 ms).

You can use a function like this one to create a delay in async code:

function delay (ms) {
  return new Promise(res => setTimeout(res, ms));
}

and use it with the await keyword like this to wait 200ms between requests and avoid the 429 rate limit response from the TomTom API:

function delay (ms) {
  return new Promise(res => setTimeout(res, ms));
}

async function fetchGeocodeResult (apiKey, address) {
  const encodedAddress = window.encodeURIComponent(address);
  const url = new URL(`https://api.tomtom.com/search/2/geocode/${encodedAddress}.json`);
  url.searchParams.set('key', apiKey);
  const response = await fetch(url.href);
  if (!response.ok) {
    throw new Error(`Response not OK (Status code: ${response.status})`);
  }
  return response.json();
}

async function example () {
  const apiKey = 'YOUR_ACTUAL_API_KEY';

  const addresses = [
    // An example address from the developer docs:
    'De Ruijterkade 154, 1011 AC, Amsterdam',
    'De Ruijterkade 154, 1011 AC, Amsterdam',
    'De Ruijterkade 154, 1011 AC, Amsterdam',
    'De Ruijterkade 154, 1011 AC, Amsterdam',
    'De Ruijterkade 154, 1011 AC, Amsterdam',
    'De Ruijterkade 154, 1011 AC, Amsterdam',
    // ...etc.
  ];

  for (const address of addresses) {
    const geocodeData = await fetchGeocodeResult(apiKey, address);
    await delay(200);
  }
}
  • Related