Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

240
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda