Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

383
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!