Even after implementing a setTimeout function, both Promises and Axios requests are still resulting in a

Recently, I've encountered an issue with the Reverse Geocode API from TomTom. The problem arises when I send multiple latitude and longitude coordinates (around 72 of them) to the API, resulting in frequent 429 responses.

To address this issue, I attempted to create a function that would introduce a 5 second delay before sending another request. TomTom recommends waiting for at least 5 seconds between requests.

I believed it was acceptable, as shown in the function below, to call one function (Topography.getTopography(latLng)) and then use the result obtained after the then call to feed into the TomTom request. Is there something wrong with this approach or could the issue lie within the setTimeout method?

Below is the code snippet of my function:

async function getTopographyData(latLang) {
    const retryTimes = 5;
    let counter = 0;
    var newObj = {};

    Topography.getTopography(latLang, options)
      .then((results) => {
        newObj.topography = results;
        newObj.latlng = latLang;
        return newObj;
      })
      .then(async (newObj) => {
        var { lat, lng } = newObj.latlng;

        let result = await axios.get(
          `https://api.tomtom.com/search/2/reverseGeocode/crossStreet/${lat},${lng}.json?limit=1&spatialKeys=false&radius=10000&allowFreeformNewLine=false&view=Unified&key=${process.env.TOM_TOM_API}`
        );

        var { addresses } = result?.data;
        var { address, position } = addresses[0];

        var [lat, lng] = position.split(",").map((p) => +p);

        newObj = {
          ...newObj,
          latlng: { lat, lng },
          address,
        };

        dispatch({ type: "setTopographyData", payload: newObj });
      })
      .catch(function (error) {
        if (
          (error.response?.status == 403 || error.response?.status == 429) &&
          counter < retryTimes
        ) {
          counter++;
          return new Promise(function (resolve, reject) {
            setTimeout(function () {
              resolve(getTopographyData(counter));
            }, 5000);
          });
        } else {
          console.log("error", error);
        }
      });
  }

Any insights or suggestions would be greatly appreciated.

Further updates indicate that while implementing num8er's solution helped, it appears there might be a larger underlying issue with TomTom. At around 45 marker points (latitude and longitude objects), the reverseGeocode lookup stops functioning properly and starts displaying errors in the console. Additionally, clicking on the link provided in the console shows successful responses in the browser?! Strange behavior indeed!

https://i.sstatic.net/2Jero.png

https://i.sstatic.net/MELZy.png

Answer №1

Consider refactoring the code with a regular loop that includes pauses and breaks to enhance readability:

async function retrieveTopographyInfo(coordinates) {
    const retryLimit = 5;
    const topographyInfo = {
      coordinates: coordinates,
      location: null,
    };

    const pauseExecution = (ms) => new Promise(resolve => setTimeout(resolve, ms));

    for (let attempt = 1, canRetry = false; attempt <= retryLimit; attempt++) {
      try {
        const topographyData = await fetchTopographyData(coordinates, options);
        topographyInfo.topography = topographyData;

        const { lat, lng } = topographyInfo.coordinates;
        const apiResponse = await axios.get(
          `https://api.tomtom.com/search/2/reverseGeocode/crossStreet/${lat},${lng}.json?limit=1&spatialKeys=false&radius=10000&allowFreeformNewLine=false&view=Unified&key=${process.env.TOM_TOM_API}`
        );

        if (apiResponse?.data) {
          const { addresses } = apiResponse.data;
          const { address, position } = addresses[0];

          const [latitude, longitude] = position.split(",").map(coord => +coord);

          topographyInfo.location = address;
          topographyInfo.coordinates = { latitude, longitude };
        }

        dispatch({ type: "updateTopographyData", payload: topographyInfo });
      }
      catch (error) {
        console.error(error);

        canRetry = [403, 429].includes(error.response?.status);
      }

      if (!canRetry) {
        break;
      }

      await pauseExecution(5000);
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sorting objects in an array according to their prices: A guide

Suppose we have the following data structure: var lowestPricesCars = { HondaC: { owner: "", price: 45156 }, FordNew: { owner: "", price:4100 }, HondaOld: { owner: "", price: 45745 }, FordOld: { owner: "", ...

What is the best way to implement asynchronous guarding for users?

Seeking assistance with implementing async route guard. I have a service that handles user authentication: @Injectable() export class GlobalVarsService { private isAgreeOk = new BehaviorSubject(false); constructor() { }; getAgreeState(): Obser ...

Ways to implement the React.FC<props> type with flexibility for children as either a React node or a function

I'm working on a sample component that has specific requirements. import React, { FC, ReactNode, useMemo } from "react"; import PropTypes from "prop-types"; type Props = { children: ((x: number) => ReactNode) | ReactNode; }; const Comp: FC< ...

How to dynamically generate Angular component selectors with variables or loops?

Looking to dynamically generate the Selector Tag in my app.component.html using a variable. Let's say the variable name is: componentVar:string What I want in my app.component.html: <componentVar></componentVar> or <app-componentVar& ...

The total height of the document's body in jQuery is not equal to the sum of the viewport height and the window's scroll top position at the bottom of the document

Why does the document height appear smaller than the window scroll top value plus the viewport height when I reach the end of the document? Shouldn't they be equal? I've been struggling with this issue for hours and can't seem to figure it o ...

Tips for calculating the difference between timestamps and incorporating it into the response using Mongoose

In my attendance model, there is a reference to the class model. The response I receive contains two createdAt dates. const attendanceInfo = await Attendance.find({ student: studentId, }) .populate('class', 'createdAt'); ...

Issue: NG0204: Unable to find solutions for all parameters in NzModalRef: (?, ?, ?)

I'm currently working on an Angular project utilizing the NZ-Zorro library, and I'm encountering difficulty understanding which parameters are causing issues with NzModalRef when attempting to run the test code coverage. The error message display ...

Tips for adjusting the dimensions of my chart using JavaScript or Jquery

Utilizing DevExtreme widgets for the creation of a line chart in jQuery as shown below: var dataSource = [{"Date Range": "August-2018", Benelux: 194, Czech_Slovakia: 128, ...

Error encountered when using the Jquery append function: Anticipated ')' issue

While working on my PHP file, I encountered an issue with an AJAX request. The request is returning the correct value, however, when attempting to use the append function in jQuery, it results in an error being displayed in the console. $.ajax({ ...

No response observed upon clicking on the li element within the personalized context menu

I created a custom context menu that pops up when you click on an li element within an unordered list. I'm trying to trigger an alert when clicking on an li item inside the context menu, but it's not working as expected. To handle this dynamic c ...

The calculator is generating console logs, but there is no output appearing on the display

I'm currently working on a calculator project using JavaScript and jQuery. I am facing an issue where the numbers are not displaying on the screen when I press the buttons, but they do show up in the console log without any errors. I would appreciate ...

In search of the mean value using PHP, jQuery, and AJAX technologies

I have successfully created a star rating system using PHP and jQuery. The issue arises when attempting to display the average rate for a specific item that I am rating; instead, the average value printed is for all items being rated. Here is my jQuery co ...

Blip Scripts: Converting JSON to JavaScript - Dealing with Undefined Arrays

I am currently working on a project to develop a bot on Blip. There are certain parts where I need to send a request to an API and then use a JavaScript script to extract elements from the JSON response. The JSON response I received from the API is stored ...

The value of document.readyState remains as 'complete' even while the page is still actively loading on the frontend

Below is the code I implemented to verify if the page has finished loading: JavascriptExecutor js = (JavascriptExecutor)Driver; pageLoadStatus = js.executeScript("return document.readyState").toString(); Despite still visibly loading, the document.readyS ...

jquery for quick search

<form method="post" action="search.php"> Commence search: <input id="search" type="text" size="30" > <div id="search_results"></div> <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> <script src="//code. ...

Using inline SVG within a Vue.js component

Recently, I embarked on a Vuejs project using @vue/cli version 3.0.0-beta.16. In my Home.vue single file component, I encountered an issue while trying to import and add inline SVG to the template. The crux of the problem lies in the fact that vue cli alr ...

What is the best way to connect or link to a HTML table row <tr>

Is there a way to trigger an alert when the user double clicks on the whole row? ...

Double submission issue with Angular form (multiple ajax requests)

My controller seems to be causing a form submission issue in AngularJS where the form is being submitted twice via a get request. Upon checking my database and the console network tab, I noticed that two submissions are logged, with the first submission sh ...

Having trouble iterating through an array of objects in Vue?

Having trouble looping through an array of objects in Vue3 <template> <div class="shadow-xl w-96 h-96 md:h-[600px] md:w-[600px] lg:my-12 lg:w-[700px] lg:h-[700px] rounded-md" > <button @click="getData">Get ...

Using ajax.actionlink to display the desired text

When using an ajax.actionlink @Ajax.ActionLink("Add Last Name", // <-- Text to display "AddTimeSeriesData", // <-- Action Method Name etc.... @id = "link") How can I extract the link text in JavaScript? I attempted to use $(&apo ...