[Vuejs]-How to make splitting two date ranges with nested functions and making a request to the API with Javascript

0👍

don’t use string date for differeces. Use timestamp, and check dates..

function requestToDataNews(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);
      });
  });
}

const onStartDate = '2021-12-27';
const onEndDate = '2022-12-27';

// convert to timestamp
const startDateStamp = new Date(onStartDate).getTime();
const endDateStamp = new Date(onEndDate).getTime();

// difference days
const diffDaysStamp = Math.ceil((endDateStamp - startDateStamp) / (1000 * 60 * 60 * 24));

if (diffDaysStamp <= 90) {
  requestToDataNews(onStartDate, onEndDate);
} else {
  const diffDate = Math.ceil(diffDays / 90);
  const dateArr = [];
  for (let i = 0; i < diffDate; i++) {
    const startDate = new Date(onStartDate).getTime();
    const endDate = new Date(onEndDate).getTime();
    const diffDays = Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24));
    if (diffDays <= 90) {
      dateArr.push({
        startDate: new Date(startDate).toISOString().slice(0, 10),
        endDate: new Date(endDate).toISOString().slice(0, 10),
      });
    } else {
      const newEndDate = new Date(startDate + 90 * 24 * 60 * 60 * 1000);
      dateArr.push({
        startDate: new Date(startDate).toISOString().slice(0, 10),
        endDate: new Date(newEndDate).toISOString().slice(0, 10),
      });
    }
  }
  dateArr.forEach((item) => {
    requestToDataNews(item.startDate, item.endDate);
  });
}

It’s example, and it’s code may be not working.. I am not testing… I’m give you idea

Leave a comment