FAQ: Requests II - async GET Requests II

This community-built FAQ covers the “async GET Requests II” exercise from the lesson “Requests II”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Web Development

Introduction To JavaScript

FAQs on the exercise async GET Requests II

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Can someone please explain this bit, and specifically the throw new Error part?

try {
    const response = await fetch('https://api-to-call.com/endpoint');
    if (response.ok) {
      const jsonResponse = await response.json();
      return jsonResponse;
    }
    throw new Error('Request failed!');

The way I understand this syntax, the code within the conditional is executed, after which an error is thrown. So, the error will always be thrown, as it is not an if else statement.
This doesn’t really make sense to me - why should an error be thrown in a code block that handles a successful response? Shouldn’t it be included as an else block rather than within the if (response.ok) block?
I’m probably misunderstanding things here, perhaps I didn’t retain enough from the error handling course. Would highly appreciate it if someone could explain this to me.

3 Likes

the error will NOT be thrown, if the response is ok, we reach a return keyword, which will hands back data to the caller and the function will exit.

Simple enough to prove with a simple code sample:

const abc = () => {
  if (true){
    return "no error";
  }
  throw new Error("help, error");
}

console.log(abc());
5 Likes

Aaaah ok, I was thinking about that but then mistakenly thought this wouldn’t happen since the return keyword was within the if statement. Thanks for clearing that up!

Different question. Why do we need the second ‘await’ statement? I see the point of the first one, which is dependent on an external resource.

const response = await fetch(‘https://api-to-call.com/endpoint’)
if (response.ok) {
const jsonResponse = await response.json()
return jsonResponse

3 Likes

I have the same question as well. I can understand that we need await for the fetch statement, since the request is being made. However for the response.json I don’t understand why do we need a promise for it? Isn’t it just a method on the response object?

As per the specifications, response.json() returns a promise, probably that is why we are using await, but still I don’t get the logic behind it why do we need it to return a promise.

2 Likes

I am not sure if i am correct but seems like we need to wait until we get .json() resolved until we can execute next line of code. Otherwise its going to be undefined. maybe?

I think so. json() returns a promise, so we have to wait for it to resolve.

1 Like

I can’t get passed Step 2. Seems pretty straightforward. My code matches that in the hint. Any ideas?

const getData = () => {
  try {

  } catch (error) {}
};

Many thanks!

I think you’re missing the async as part of the arrow function. As in async() => {}

Hi
I have question regarding the following topic can you please clear me this concept of async…await.
When we are using await in async function we wait for the promise to resolve so how the we are achieving the await` allows a program to run while waiting for a promise to resolve..
async GET Requests II

As far from the following lesson The await Operator it says somthing like this

await is an operator: it returns the resolved value of a promise. Since promises resolve in an indeterminate amount of time, await halts, or pauses, the execution of our async function until a given promise is resolved.

can you please clear it up for me

Thanks

And what is the question?

async runs asynchronous, within this asynchronous running awaits wait until the promise has been resolved.

There are 2 statements in 2 different chapters as i mentioned in my last message.

  1. await halts the execution of the async function The await Operator
  2. await` allows a program to run while waiting for a promise to resolve. async GET Request II

I am getting confused :frowning: with these 2 statements (contradicting each other). Can you please put a little light here.

Kind Regards

1 Like

awaits wait till the promise is resolved.

await can only be used in an async function. await allows a program to run while waiting for a promise to resolve, might be better phrased async is allows your code to run in parallel.

So the await will wait for the promise, but that happens in parallel thanks to async.

1 Like

Hi,
I’ve just finished the Requests module and in all the exercises shown i see the following code in the index.html:

</main>
  <script src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
  <script src="public/main.js"></script>
  <script src="public/helperFunctions.js"></script>
</body>
</html>

My first question what is the first script (src=‘https://code.jquery.com/jquery-3.1.0.min.js’) entry for ?

And my second question.
Inside the main.js we use functions that are written in the helperFunctions.js, but there’s no import/export of these, so how are we able to use them without importing them first ? see code for main.js below (from Async GET Request example), where the renderResponse function is written inside the helperFunctions.js file.

// Information to reach API
const url = 'https://api.datamuse.com/words?';
const queryParams = 'rel_jja=';

// Selecting page elements
const inputField = document.querySelector('#input');
const submit = document.querySelector('#submit');
const responseField = document.querySelector('#responseField');

// AJAX function
const getSuggestions = async () => {
  const wordQuery = inputField.value;
  const endpoint = url+queryParams+wordQuery;
  try {
    const response = await fetch(endpoint, {cache:'no-cache'});
    if(response.ok) {
      const jsonResponse = await response.json();
      renderResponse(jsonResponse); 
    }
  } catch (error) {
    console.log(error)
  }
}

// Clear previous results and display results to webpage
const displaySuggestions = (event) => {
  event.preventDefault();
  while(responseField.firstChild){
    responseField.removeChild(responseField.firstChild)
  }
  getSuggestions();
}

submit.addEventListener('click', displaySuggestions); 

Thanks,

Alex

Your question is excellent @rabiolas. Let me try and answer.

There are 2 different exercise environments to illustrate the results of this JavaScript course: one using nodeJS and one using the browser and jQuery. You can see the difference on the right panel

  • when the outcome is illustrated using nodeJS the righmost panel shows the console (terminal) screen. In this case we need to import the code between files
  • when the outcome is a browser the righmost panel shows the browser display, as in this exercise. Then all the codes are (kind of) imported by the browser with the script tags
  • the 1st script tag imports the jQuery functions in the browser
  • the 2nd script tag imports the main.js
  • the 3rd script tag imports the helperFunctions.js

Hope it’s clearer.

In the beginning of the conditional statement if(response.ok) response is the object that can be called anything. Is that correct? So, could we for instance write if(output.ok)?

Also, I am a little fuzzy on how json() works. According to mozilla it reads, “Note that despite the method being named json() , the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.” Where does this parsing take place?

if here:

const response = await fetch(endpoint, {cache:'no-cache'});

you are free to choice a variable, so yes, you could name this variable output, but I find response to be a more accurate description

I assume within this method/function

Thanks! For the second question, I mean like what is doing the work? Is it a web api or is it something else?

.json() is a method implemented by other developer(s), which is doing the parsing for us.

Which happens in the browser javascript engine

1 Like