Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
Fetch API inside a class function

I'm having trouble with destructuring an object that is returned from the fetch api in my Aztro class.

I've tried various way to destructure it at random with no success....

If i return it instead of console logging, how do i access it? See the code and comments for further clarification of my questions.

The reason i want to do this is because the api will only return one zodiac sign at a time.

 class Aztro {
  constructor(sign){
    this.sign = sign
  }
  getData(){
    return fetch('https://example/?sign=' + this.sign + '&day=today', {
      method: 'POST'
    })
    .then( response => response.json() )
    .then( data =>  {
      console.log(data) // how do I destructure this if it's returned and not just console.log()
    })
  }
}

let aries = new Aztro('aries')      // Can pass in zodiac signs to fetch data
let aquarius= new Aztro('aquarius')

aries.getData()     // this logs the json data in the console....

// EDIT this is how I tried to destructure it 

const {description} = aries
const {description} = aries.getData() // this returns Object promise when i tried to output it to the dom 
const {description} = Aztro
 
about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

You can access the fetched data in two manner:

1- using promise chain, like this:

aries.getData().then(data => console.log(data))  

2- using async/await to fetch data.The important point in using async/await is that you have to call await keyword just inside an async function (the reason I defined app function in below code) like this:

class Aztro {
  constructor(sign){
    this.sign = sign
  }
  async getData(){
    const response = await fetch('https://example/?sign=' + this.sign + '&day=today', {
      method: 'POST'
    })
    const data = await response.json();
    return data;
  }
}

async function app(){
  let aries = new Aztro('aries')      // Can pass in zodiac signs to fetch data
  let aquarius= new Aztro('aquarius')
  const data = await aries.getData();
  console.log(data);
}
app();
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!