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

129
Visualizações
pending promise inside async/await

I wast trying to fetch some data in componentDidMount and then set it to state, wrote an async await function for the same. But if i was trying to set the state with the values right after await, the value was getting set to a pending promise but console logging would give the correct output. For that reason i called the getData().then() to set the data, why it was giving pending promise can someone clear the concept out here?

componentDidMount() {

    async function getData() {
      const baseUrl = `https://........`;
      const response = await fetch(baseUrl);

      if (response.status === 200) {
        const json = await response.json();
        const { data } = json;
        //console.log(data) =>correct output
        return data;
      }

      return null;
    }

    getData().then(data => {
      this.setState({ names: data });
    });
   
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

getData is an async function that you syncronize your fetch call inside. So it returns a promise. You're console logging inside that function after response fetched. So it logs the data.

You can think it as Fetch function that you use, you're awaiting it because it's a async function and you should await for the response. It's the same for the getData too. No matter how you wait, use then or await.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can simply do it like that:

    componentDidMount() {
        const baseUrl = `https://........`;
        fetch(baseUrl)
        .then((response) => response.json())
        .then(result => {
            this.setState({ names: result.data});
        });
    }

about 4 years ago · Juan Pablo Isaza 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