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

118
Visualizações
JavaScript, async await is returning a promise instead of the result

I have the below function. Why am I getting Promise { <state>: "pending" } when calling GetProfile("username")? What should I do?

const GetProfile = async (username) => {
  await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => {
    console.log(resp.json());
  });
};
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

resp.json() returns a Promise and that's what you are console logging. It should resolve before getting the actual data. Since you are in an async function, you could do as below. Notice there is no need to have this then block you have.

const GetProfile = async (username) => {
  const res = await fetch(`${host}/api/v1/getprofile/${username}`);
  const data = await res.json();
  return data;
  });
};
about 4 years ago · Juan Pablo Isaza Relatório

0

That's normal async function behavior in javascript, they return promises.

In React, you can keep the value in a state.

const [profile,setProfile]=useState(null)

    useEffect(()=> {


        const GetProfile = async (username) => {
           const profile = await fetch(`${host}/api/v1/getprofile/${username}`).then(resp => resp.json());
           setProfile(profile)}

        GetProfile(username);

    },[username])
about 4 years ago · Juan Pablo Isaza Relatório

0

Because you're using .then after your async call, and resp.json() also returns a Promise which isn't being returned by your .then() call.

What happens in your case is:

const response = await fetch(`${host}/api/v1/getprofile/${username}`)
return response.json();

And because the json() function is a Promise itself (which isn't await'ed), the read of the json() call is the 'Pending' Promise that you're getting.

So to solve this, try either:

await fetch(`${host}/api/v1/getprofile/${username}`).then((resp) => resp.json())

or

const response = await fetch(`${host}/api/v1/getprofile/${username}`)

return await response.json();
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