Log in from a computer to take this course

You'll need to log in from a computer to start Learn Intermediate JavaScript. But you can practice or keep up your coding streak with the Codecademy Go app. Download the app to get started.

apple storegoogle store
Learn

In the previous exercise, we set up the POST request by providing the endpoint and the object containing all the necessary information. In this exercise, we’ll handle the response.

The request returns a Promise which will either be resolved or rejected. If the promise resolves, we can check and return that response. We will chain another .then() method and handle the returned JSON object and display the information to our webpage.

Let’s implement this knowledge into our code!

Remember that if you reset the exercise at any point, you will have to paste in your API key again at the top!

Instructions

1.

Chain a .then() method at the end of the fetch() function we wrote in the previous exercise. As its first argument, pass an arrow function as a callback that takes response as its single parameter.

2.

Inside the callback function of the .then() method, use a conditional statement to check the value of the ok property of response. If it evaluates to a truthy value, return response.json().

Run the code.

3.

Below the curly braces of the conditional statement, throw a new Error in case response.ok is falsy.

The error message should be 'Request failed!'.

4.

As the second argument of the .then() method, add another arrow callback function that takes networkError as a single parameter.

Log the networkError.message inside of the callback function.

By adding this second callback, you’re safeguarding yourself in the rare event that the network returns an error!

5.

Chain another .then() method to the end of the previous .then() method.

6.

Pass in an anonymous arrow function as an argument for our second .then(). This callback function will take jsonResponse as its single parameter.

Inside the callback function, call renderResponse() and pass in jsonResponse.

The renderResponse() helper function can be viewed at public/helperFunctions.js.

Run the code.

Put in any URL in the text field, and then click the shorten button on the webpage. Make sure you include the entire link, including 'http://' or 'https://'.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?