0

I make calendar for my project and need to use seved data from server inside "function CalendarPicker()". I get data from server as promise and try use it inside "function CalendarPicker()" but always get undefined. How can I force it?

async function _getMeetingsData() {
    let response = await fetch('calendar');
    let data = await response.json();
    data = JSON.stringify(data);
    return data;
}

function CalendarPicker() {
    //Get meeting data
    this.meetingsData = _getMeetingsData();

    this._insertNavigationButtons();
    this._insertHeaderIntoCalendarWrapper();
    this._insertCalendarGridDaysHeader();
    this._insertDaysIntoGrid();
    this._insertCalendarIntoWrapper();
}

const myCalender = new CalendarPicker();
Gregory Sidh
  • 115
  • 10
  • Anything that uses `this.meetingsData` needs to be async as well so it can await `_getMeetingsData`. – evolutionxbox Jan 20 '21 at 22:18
  • It's probably better to make an async factory that returns a fully initialized CalendarPicker. You can't `await new`, so if you don't do this, you will create a new CalendarPicker, but then you can't use until its' ready, and there's nothing to await. – Evert Jan 20 '21 at 22:47
  • Thank U for answer man, I tried to call _getMeetingsData with the await and I always get the error. But you provide me really useful article! Thank U! – Gregory Sidh Jan 21 '21 at 07:47

2 Answers2

0

Because you have defined _getMeetingsData as an async function, you need to call _getMeetingsData with the await keyword. In that case, you also need to make CalendarPicker an async function. Alternatively, you can call _getMeetingsData within a promise construct in your CalendarPicker function.

Tuhin Paul
  • 558
  • 4
  • 11
0

You need to have an async constructor (arguably odd) or await for your data, because every async function is implicitly a promise, even if it synchronously returns a value ... so:

function CalendarPicker() {
  //Get meeting data ... then
  _getMeetingsData().then(meetingsData => {
    this.meetingsData = meetingsData;
    this._insertNavigationButtons();
    this._insertHeaderIntoCalendarWrapper();
    this._insertCalendarGridDaysHeader();
    this._insertDaysIntoGrid();
    this._insertCalendarIntoWrapper();
  });
}

This works, but if you have any prototype method that needs that data, you better store the promise:

function CalendarPicker() {
  //Get meeting data ... then
  this._meetingsData = _getMeetingsData().then(meetingsData => {
    this.meetingsData = meetingsData;
    this._insertNavigationButtons();
    this._insertHeaderIntoCalendarWrapper();
    this._insertCalendarGridDaysHeader();
    this._insertDaysIntoGrid();
    this._insertCalendarIntoWrapper();
  });
}

CalendarPicker.prototype.doThings = function () {
  this._meetingsData.then(() => {
    console.log(this.meetingsData);
  });
};
Andrea Giammarchi
  • 3,038
  • 15
  • 25