How do you access and store the values/properties of a “fulfilled” promise?



I’m trying to build an object that renders details of a certain planet. I use the fetch method and it returns a promise. How do I get the values from the [[PromiseResult]] object in order to populate the details in “render()”. I tried to call fetchPlanetData().then(data=>data.(any property) from the ${ } in render(they have placeholders now) but it always returns “undefined.” Thanks in advance.

class PlanetDetails {
  constructor(planet) {
    this.planet = planet;
    //this.fetchPlanetData();
    this.render();
  }

  async fetchPlanetData() {
    const result = await fetch(`https://api.le-systeme-solaire.net/rest/bodies/${this.planet}`);
    this.data = await result.json();
    return this.data;
  }

  render() {
    const hook = document.querySelector('.moons');
    const container = document.createElement('div');
    container.className = 'container';
    container.innerHTML = `
    <p>The average temperature is:${'averageTemp'}</p>
    <p>The escape velocityis:${'escape'}</p>
    <p>The gravity is ${'gravity'} times that of Earth's.</p>
        `;

    hook.append(container);
  }
}

const planetDetails = new PlanetDetails('neptune');

console.log(planetDetails.fetchPlanetData());``

Answer

Instead of putting this.render in the constructor, make a new async method called init and call it from the constructor instead. await the data from fetchPlanetData, assign it to this.data, and then call this.render.

Note: it doesn’t look like you’re using any data from this.data in your render method. When you code ${'averageTemp'} did you mean ${this.data.averageTemp}, for example?

class PlanetDetails {

  constructor(planet) {
    this.planet = planet;
    this.init();
  }

  async init() {
    this.data = await this.fetchPlanetData();
    this.render();
  }

  async fetchPlanetData() {
    const result = await fetch(url);
    return result.json();
  }

  ...

}


Source: stackoverflow