0

i'm implementing Toast Ui Calendar in my php/js app and in the flow of javascript execution the program encounter this function:

function setSchedules() {
    cal.clear();
    generateSchedule();
    cal.createSchedules(ScheduleList);
    refreshScheduleVisibility();
}

When i refresh the page to visualize the events retrived from db via axios and php function, the calendar is empty, then if a select month view or go back one week and come back to the current week the events are rendered.

The problem seam to reside in the function generateScedule() which is declared inside a schedules.js file and that declare and fulfill the ScheduleList array to pass to the createSchedules function, follow the code:

var ScheduleList = [];
function generateSchedule() {
axios({
  method: 'post',
  url: 'path-to-data',
})
.then(function (response) {
  ScheduleList = [];
  let data = response.data;
  for(let key in data){
    ScheduleList.push(data[key]);
  };
})
.catch(function (error) {
 console.log(error);
});
 return ScheduleList; //with or without this return the result doesn't change
}

It's like if the array ScheduleList at first is returned empty (whithout waiting) while the function is still fulfilling it, console.log inside varoius parts of the function confirm it.

If i fulfill the array manually with pasted json data, everything is returned immediately an fine.

I know it has probably to do with javascript stacks etc..

Any help would be appreciated.

Thanks a lot in advance!

1 Answers1

0

Because axios is async so the ShceduleList stay empty, the return is executed before the loop of data.

Try this :

function generateSchedule() {
  return axios({
    method: 'post',
    url: 'path-to-data',
  })
    .then(function (response) {
      var ScheduleList = [];
      let data = response.data;
      for (let key in data) {
        ScheduleList.push(data[key]);
      };
      return ScheduleList;
    })
    .catch(function (error) {
      console.log(error);
    });
}