PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] Why does axios.get(url).data not work? (axios GET requests and property accessors; JavaScript)

 October 14, 2022     async-await, axios, get, javascript, properties     No comments   

Issue

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.


Solution

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


Answered By - Barmar
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing