Skip to content
Advertisement

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());``

Advertisement

Answer

Seems you are missing understanding of Promises and Async Await. Added link for all for learning.

Promises are different from normal function calls, they don’t return values like synchronous methods, they return response when they are fulfilled and code execution doesn’t stop on Promise call, so How does promise returns data – Using two methods resolve and reject.

Async await is just a wrapper over promises to make promises look like synchronous code but behind the scenes it’s always asynchronous.


In promises, you get either resolved or rejected after fulfilment and usually we put the data inside the resolve part and errors in reject part. In async-await the same gets converted into try...catch blocks. As return a value x from an async function always means Promise.resolve(x) so this data can be used inside a then method or try block. And any Promise.reject or throw can be captured in the catch block.

class PlanetDetails {
  constructor(planet) {
    this.planet = planet;
    this.resolvePlanetData();
  }

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

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

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

    hook.append(container);
  }
}

const planetDetails = new PlanetDetails('neptune');
.moons {
  padding: 10px;
  border: 1px solid aqua;
  margin: 10px;
}

.container {
  border: 1px solid gray;
  padding: 5px;
  margin: 5px 0;
}
<div class="moons">

</div>

Notice that I have used try...catch in fetchPlanetData but not in resolvePlanetData because fetch or .json() can throw error or reject in many situations which is handled in try catch but I know that fetchPlanetData will always resolve as no throw is there so I can use it withouttry...catch safely.

Also, I am assuming you want to use this.data in render method hence updated the same.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement