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

382
Visualizações
Why does axios.get(url).data not work? (axios GET requests and property accessors; JavaScript)

I have an async function that is requesting an object with a name and id property. I understand that you can't return await axios.get(url).data.name without getting kicked into the catch statement.

My question though is what is the reason that it doesn't work?

async function getConstellationNameById(id) {
  const url = `${BASE_URL}/constellations/${id}`;

  try {
    return await axios.get(url).data.name;
  } catch (error) {
    throw `Constellation with id of ${id} could not be found.`;
  }

}

If I store the GET request in a variable instead and then use dot notation to access the name property it works:

try {    
    //return axios.get(url).data.name;
    const constellation = await axios.get(url);
    return constellation.data.name;
  }

Is it because dot notation has a timing to it? Therefore, while the GET request is in the event queue, the .data.name portion is considered sync code and fails to get anything? I had thought since it's being executed all in one line, property accessors would execute along with the GET request?

Or is it because of another reason?

I also thought you could only access a Promise object's properties within .then() and .catch() statements; is that not the case?

Apologize in advance if I'm misusing any terminology as I'm still learning! Just really want to make sure I understand the reasoning before continuing.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

. has higher precedence than await, so your code is equivalent to:

return await (axios.get(url).data.name);

so axios.get(url).data.name would need to be a Promise. But the promise that you want to await for is returned by axios.get(url). Add parentheses to force the proper grouping:

return (await axios.get(url)).data.name;
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