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.