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

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

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 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