What is the best way to handle data that is received within nested functions in JavaScript?

I'm working on a task that involves fetching news within specific date ranges using nested functions. Currently, my API fetches data for up to 90 days to prevent timeout errors. However, I now need to retrieve data spanning a whole year. My approach is to divide the year into 90-day chunks. How can I modify the for loop to stop when the required data is fetched?

Below is a snippet of my code:


function fetchDataBetweenDates(startDate, endDate) {
    return new Promise((resolve, reject) => {
      http.get(`/test=&start_date=${startDate}&end_date=${endDate}`, { timeout: 40000 })
        .then((response) => {
          if(response.data.response_code === 200){
            resolve(response.data);
          } else {
            reject(response.data);
          }
        })
        .catch((error) => {
          reject(error);
        }).finally(() => {
          commit('loadingBar', false);
        });
    });
 }

commit('loadingBar', true);

let startDate = '2022-12-27';
let endDate = '2021-12-27';

const daysDifference = tools.getDifferentDaysRange(endDate, startDate, 'days');
const currentNewsData = [];

if (daysDifference > 90 && daysDifference <= 365) {
   for (let i = 0; i < Math.ceil(daysDifference / 60); i += 1){
     startDate = moment(endDate).subtract('months', 2).format('YYYY-MM-DD');
     const newsData = fetchDataBetweenDates(startDate, endDate);
     if (newsData.is_success) {
       currentNewsData.push(...newsData.data);
     }
   }
 }
I anticipate the calculation to update the start date as follows: If endDate = '2022-12-27', then startDate would be '2022-10-27'. Additionally, I aim for the loop to terminate once the response data is complete without backtracking through past dates.

Answer №1

Experiment with utilizing nested loops for this task. The primary loop will iterate from 1 to 365, while the secondary loop will cover a span of 90 days. After each 90-day cycle is completed, advance the primary loop by 90 and repeat the inner loop process.

Answer №2

In order to achieve this goal, you can incorporate a break statement within your loop to terminate the iteration once the specified condition is met. For instance, you can introduce a check to verify if the length of the newsData.data array matches the maximum number of items permitted by the API (which could be either 90 or later on possibly 60). This strategy ensures that the loop exits promptly upon reaching the API's limit, preventing unnecessary processing through earlier dates.

It's essential to note that you must also dynamically update the endDate variable during each cycle of the loop to consistently retrieve data for the upcoming 60-day period. To accomplish this, simply assign the value of startDate to endDate at the conclusion of each iteration:

if (differentDays > 60 && differentDays <= 365) {
  for (let i = 0; i < Math.ceil(differentDays / 60); i += 1){
    startDate = moment(endDate).subtract('months', 2).format('YYYY-MM-DD');
    const newsData = requestToDataNews(startDate, endDate);
    if (newsData.is_success) {
      currentNewsData.push(...newsData.data);
      if (newsData.data.length === 60) { // alternatively, adjust to 90 depending on your preference
        break;
      }
    }
    endDate = startDate;
  }
}

This method enables you to acquire data in increments of 60 days and cease operation once the desired date range has been reached.

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

having difficulty placing 3 pop-up windows on a single page

Struggling to implement multiple popups on my page, each with a unique ID assigned. Any assistance would be greatly appreciated. Here is the code snippet: .fa { font-size: 50px; cursor: pointer; user-select: none; } .fa:hover { font-size:20px; t ...

Dynamically linking tabbable tabs is a useful technique that allows for

I have been working on an app that organizes websites into groups displayed as tabs in a tabbable navigator using Twitter Bootstrap. The idea is that each time a new group is added, a new tab should appear. Currently, this is how it looks: The functionali ...

Ways to remove the uploaded document

I have been tasked with uploading a file. The file comes with a remove button, which can be pressed to delete it. Below is the code I used: The code snippet is as follows: <div id="main"> <p id="addfile1">Add File</p> <div id ...

The v-tabs component in Vuetify seems to be unable to fill 100% of the available

When using the v-tabs component, I noticed that it doesn't take up 100% of the height. Upon further inspection, I found that all the tab items (tab contents) are wrapped inside a <div class='v-tab__items'> your content </div ...

Vue filter and the importance of not modifying the vuex store state without using mutation handlers

Learning Vue is an ongoing journey for me, but I'm struggling to grasp why this particular error keeps popping up. Error: [vuex] Do not mutate vuex store state outside mutation handlers. Let's take a look at the code snippet in question: ...

Tips for creating a mandatory textarea input field

It's pretty straightforward - I have a textarea that is set to required, but it only alerts the user if you actually click inside the text area. If you try to submit without clicking inside, it won't prompt the alert. Take a look at this Fiddle ...

Performing an XMLHttpRequest in the same JSP file using Javascript

I am working on a JSP file that contains three dropdown boxes labeled "countries", "regions", and "cities". My goal is to populate the regions based on the selected country, and the cities based on the selected region. I have managed to achieve this using ...

Modifying the CSS Property of a Non-React Element within a React Application

I am currently in the process of developing a React-based application that will operate within a Wordpress page. The application is mostly self-contained, but I am interested in being able to toggle the visibility of a div element on the page that is not p ...

Spline does not align with ExtrudeGeometry in the Three.js library

When creating a track for my game, I encountered an issue where the spline I used to calculate the position of my ship did not completely match the geometry. Is there something wrong with my approach? Click here for an example of the shape used for extrus ...

Replace minor components (SVG) within the primary SVG illustration

I'm interested in transforming SVG elements into the main SVG element. For example, let's say the black square represents the main SVG element. I want to change elements 1, 2, and 3 to different SVG elements using JavaScript code. However, I am u ...

Encountering TypeError and Warning while passing an object as a prop in Vue.js

I've been encountering an issue where I'm trying to pass an object into my child component, but it's showing up as undefined. In my parent component, here's what I have: <template> <section id="cart-page" class=&q ...

Observing Arrow Keys as '0' during keypress event execution

When using Firebug for debugging in Firefox version 8.0.1, I set up a keypress event handler on an editable div. While every key press is successfully displayed in the console, I am encountering an issue with the arrow keys - the value of e.which in the co ...

Prevent text from wrapping when using jQuery to animate font size

I have a unique way of showcasing content in a preview format by utilizing em units for scaling and adjusting the root font size to increase or decrease. When users click on the preview, the full content is revealed with an animation that scales the font s ...

Receiving an error message stating "Unable to execute method 'toLowerCase' on an undefined object" while attempting to use grid.setFilter(...)

I am trying to programmatically set my filter plugin for an enhanced grid. Here is the approach I am taking: //concat query string console.log(queryString); grid.setFilter(queryString, 'logicany'); However, I am encountering an error: Uncaught ...

Storing a byte array in a local file using JavaScript: A Step-by-Step Guide

Recently, I encountered an issue while working with an openssl certificate. Specifically, when I tried to download the certificate from my API, it returned byte arrays that I needed to convert to a PEM file in order to access them through another API. The ...

Two adjacent divs, flexible with maximum width

I want to create two side-by-side DIVs, with the left one always containing text and the right one possibly being empty. If the right DIV contains text ... the width of the left DIV should adjust to match the text width, but only up to 50% of the parent D ...

Issue with LokiJS: The DynamicView().branchResultSet method does not apply sorting to the collection

I'm encountering an issue retrieving data from a branchResultSet after applying the applySort function on the view. I'm utilizing this method to restrict the result set to 10 records for better performance, rather than fetching the entire dataset ...

The Quasar Icon Genie CLI transforms square icons into rectangle shapes

Is there a way to prevent cropping when generating icons for my Capacitor app using Icon Genie CLI? I have a 512x512 icon that I am passing to the tool, but the resulting icons are cropped to a rectangle and have a white background on iOS. Here is an examp ...

Video DTO not defined with the utilization of a brightcove player

Hey there, just a quick question from a newcomer.. I tried following the example at to extract information about the current video DTO in order to display it on my page. However, when accessing it via JS, the value of the video DTO always turns out to be ...

Deploying a live Laravel application with Vue.js

I recently finished developing a project on laravel with vue js. The frontend of my project is entirely built using vue js, while the backend utilizes laravel APIs. Here is an overview of my project structure: --app --bootstrap --config --database --fonte ...