How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts.

Promise.all(
orders.map(order => this.api.getURL(order.resource_url).catch(() => null))
).then(responses => {
  const successfulResponses = responses.filter(response => response != null)
  for(let data of successfulResponses) {
       // additional requests are made with the retrieved data here
  }
});

I have more than 50 orders to process, but I can only handle a maximum of 50 at once due to the API restrictions. Therefore, in my service, I track the timestamp of the first request made. If the time difference between subsequent requests is over 60 seconds, I reset the request limit to 50. If it is less than 60 seconds, I check if there are available requests remaining. If yes, I proceed with the request; otherwise, I wait for one minute:

sleep(ms){
    return new Promise(resolve => setTimeout(resolve, ms));
}
async getURL(){
      if(!this.date){
        let date = new Date();
        this.date = date;
      }
      if((new Date().getSeconds() - this.date.getSeconds() > 60 )){
        this.maxReq = 50;
        this.date = new Date();
        return this.http.get(url, this.httpOptions).toPromise();
      } else {
        if(this.maxReq > 0){
          this.maxReq -= 1;
          return this.http.get(url, this.httpOptions).toPromise();
        } else{
          console.log("wait");
         await this.sleep(60*1000);
         this.maxReq = 50;
         this.date = new Date();
         return this.http.get(url, this.httpOptions).toPromise();
        }
      }
  }

However, the code in app.component.ts does not properly synchronize with the getURL() function, leading to an issue where too many requests are sent too quickly. How can I resolve this problem?

Answer №1

Dealing with promises and multiple async functions can be tricky at times. It's crucial to remember that using the await keyword is essential on the root line calling the function to ensure all functions wait accordingly.

If you encounter issues like your await this.sleep(60*1000); line seeming to not wait as expected, it could be due to missing an await or a similar approach like .then before calling getURL().

A smart way to identify such problems is through debugging tools like Chrome DevTools. I recommend setting breakpoints and closely monitoring how your code progresses through each line.

For clarification, consider this simplified example:

// Example showcasing incrementing numbers from 1 to 3 after a 1-second delay each time.

async function loop() {
    for (i = 1; i <= 3; i++) {
        console.log('Input start');
        /* By using 'await' here, we ensure proper sequencing of async operations.
           Without it, the subsequent lines would execute prematurely
           while awaiting the outcome of the async operation.
           --- This could be where the issue lies in your code. --- */
        await aSync(i);
        console.log('Input end');
    }
}

async function aSync(num) {
    console.log('Return start');
    /* By including 'await' here, we allow a 1-second delay before proceeding.
       Without it, a pending promise would be returned immediately each time. */
    let result = await new Promise(
        function(rs, rj) {
            setTimeout(
                function() {
                    rs(num); // Resolving the promise with the provided number.
                }, 1000
            )
        }
    );
    console.log(result);
    console.log('Return end');
    
}

loop();

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

Utilizing custom parameter types for Cypress Cucumber preprocessor with TypeScript

I have been using cypress-cucumber-preprocessor with cypress and typescript. While exploring the custom parameter types feature, I came across a possibility to define custom parameter types in my step definitions file. However, I am facing challenges when ...

Convert a multidimensional array into a string using JavaScript

Currently, I'm in the process of generating an invoice for a collection of books and my intent is to submit it using ajax. However, when attempting to json encode the array of books within the invoice, I am encountering a setback where the value keeps ...

Simply interested in extracting the JSON Class specifically, not all of the data

Looking for a way to extract only text from a specific class using $.getJSON and YQL. Currently, it retrieves all data and removes tags. Is there a method to achieve this? function filterData(data){ // remove unwanted elements // no body tags ...

Stop a user from adding duplicate tasks

I have developed a JavaScript code for creating a todo list. Currently, I am working on the phase of adding tasks to the list. The user wants to ensure that if a task is entered once, it cannot be entered again. const taskInput = document.getElementById(&a ...

What is the best way to include a form within every row of an HTML datatables structure?

I have a regular table that is populated with data fetched via Ajax, and it appears like this: Ajax <script> $(document).ready(function() { $('#mytable').DataTable( { "ajax": "myurl", "dataType": 'json', ...

Execute the Angular filter again when there is a change in the scope

I am currently working on an application where Users have the ability to switch between kilometers and miles for unit distances. To handle this, I created a custom filter that converts the distances accordingly: app.filter('distance', function() ...

What is the reason that the attr function fails to function in this particular scenario?

I want to implement a functionality where clicking on an input field clears its value, but I can't seem to make it work. Here is the HTML code: <input id='input' type="text" name="phppostvar" value="clear this"></input> This i ...

Conceal or reveal buttons using JavaScript

I am struggling with a function that is supposed to hide certain buttons and create a new button. When I click on the newly created button, it should make the previously hidden buttons visible again. However, the function does not seem to work properly. ...

The subsequent menu selection will be based on the chosen menu value

I am attempting to accomplish the following: https://i.sstatic.net/JffUWC02.png Essentially, I need a select options menu with labels where selecting an option will display a corresponding value. These values should then become labels for a second selec ...

The Child component is unable to render initially due to the Context API being undefined during the first render of the Child component

I'm struggling to ensure that a child component only renders when the Context API state I've set up is fully mounted. The Parent component fetches data from the server and sets the state based on the received information. Initially, I keep gettin ...

JavaScript code can be used to access data from a JSON file and present the flower and color information in separate unordered lists

How can I retrieve data from a JSON file in JavaScript and display flowers and colors in separate unordered lists? I am having trouble adding it. fetch('dataFiles/midterm.json', { method: 'GET', mode: 'no-cors' ...

Press on a list item within Angular Material 2/4

My goal is to trigger a function when clicking on any row of a list or table. I have not been able to achieve this, so now I am attempting to have the function called when clicking on the first column of each row. The structure of my component.html, which ...

The default filter in Angular Material Autocomplete is failing to function as expected

I've implemented the Autocomplete feature from Angular Material in my project, but I'm facing an issue with the search filter. It seems that the default filter provided in the example is not working as expected – instead of filtering based on m ...

Encountered an issue with retrieving schema during self-referencing validation with openapi generator

I created an openapi specification and now I am looking to generate a client for it. openapi.yaml After some research, I decided to use the openapi generator to create a typescript-axios client. This is the command I used: openapi-generator-cli generate ...

I need to verify that the input type for time is valid, starting from today's date and extending beyond the current

<input type="date" onChange={(e)=>setDate(e.target.value)}/> <input type="time" onChange={(e)=>setTime(e.target.value)} /> If the selected date is after today and the time is after the current time, display a valida ...

AngularJS: Component fails to load controller

I am managing a directory structure that looks like this --- js/app.js ------- components ----------- header -------------- headerComponent.html -------------- headerComponent.js -------------- headerController.js Within index.html, I have the following ...

What is the correct way to integrate knex using inversify?

Is there a way for me to set up knex and utilize the Inversify dependency injector to inject it wherever it is required? ...

Combining React state value with an HTML tag would be a great way

I am facing an issue while trying to concatenate the previous value with new data fetched from an API using a loop. Instead of getting the desired output, I see something like this: [object Object][object Object],[object Object][object Object] Here is ...

Troubles with importing/resolving components in Vue 3

Just starting out with Vue and following tutorials to learn. I've created a component called Header.vue and attempted to import it into App.vue. This is the setup: code structure Here is App.vue: <template> <Header /> </template&g ...

Issue with reading the current length of an array object in a while loop in Angular 6

After successfully splitting an array into parts, I decided to add some filters to only include the items in the list that have an action status of (4). However, I encountered a problem where the while loop couldn't read the length of the array. This ...