0

Ive already had one question axios in javascript function to return data about this but it has been closed and I am still fighting this.

However I had some progress of sort.

class Api {
  getPin = () => {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => response.json())
      .then((json) => this.getResults(json));
  };

  async getResults(data) {
    let pin = await data;
    console.log(pin.id);
  }
}

let api = new Api();

api.getPin();

This will get API call and I am able to console log it (this is after 10 hours looking into this :'-() Ideally I would like to use the result elsewhere in the app

Could someone please help? I am struggling with this

EDIT:

class Api {
  getPin = () => {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then((response) => response.json())
      .then((json) => this.getResults(json));
  };

  getResults(data) {
    // console.log(data);
    return data;
  }
}

let api = new Api();

let pin = api.getPin();

console.log(pin);

if I get rid off the async and await and return data from function I am getting undefined when trying to console log. WHat am I still missing?

Jakub Koudela
  • 160
  • 1
  • 18
  • `await data` doesn't make sense – Taplar Nov 04 '20 at 18:09
  • Your logic works fine if you remove the await off of the data, and the async off of the getResults method – Taplar Nov 04 '20 at 18:13
  • Tip: sort answers to the duplicate question by votes before reading. In short using " the result elsewhere in the app" _without_ implementing a mechanism to wait for the data to be returned from the server is impossible - it would be like trying to access DOM elements before the document is ready. – traktor Nov 04 '20 at 23:02

0 Answers0