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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.