Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda