[Vuejs]-How do I stop when data comes in nested functions w'th Javascript?

0๐Ÿ‘

Try a nested loops. The outer loop to be 1 to 365 and the inner loop will be 90 days. Once the 90 days is over increment the outer loop by 90 and do the inner loop again.

0๐Ÿ‘

To achieve this, you can use a break statement within your loop to exit the loop when the condition you want is met. For example, you can add a check to see if the length of the newsData.data array is equal to the maximum number of items that the API allows you to fetch (in your case, 90 or if you want later on 60?). This way, the loop will exit as soon as the API returns the maximum number of items, and it will not continue iterating through the past dates.

Keep in mind that you will also need to update the endDate variable in each iteration of the loop, so that you are always fetching the next 60-day range of data. You can do this by setting endDate to startDate at the end 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) { // or you can make this one 90 if you want to keep it at 90. it's not clear which amount you wanted it. 
        break;
      }
    }
    endDate = startDate;
  }
}

This should allow you to fetch the data in 60-day increments, and stop as soon as you have reached the desired date range.

Leave a comment