03-fetch() method
FETCH
In this module, we'll add the fetch method for our GET request and take a look at the results.
fetch()
Just like we've practiced in other small applications, let's use fetch
to start talking to the NYT API. Now that the url has been created, we can send a request to the API using the information specified. Add the following to the bottom of the fetchResults
method, right before the ending curly bracket:
Let's analyze a little: 1. Remember that fetch
is a reserved keyword in JavaScript that allows us to make a request for information, similar to using a GET request with HTTP. The url is given to fetch as a parameter, which sends the request to the url. 2. Meanwhile, it creates a promise containing a result object. This is our response. Remember that we use promises when we have asynchronous, long-running operations. The fetch gets the network resource, which might take a long time to resolve. It will convert the response into a json
object by returning the result.json
function. 3. That json
object is used in another promise (set off by the second .then
) to send the information received to another function. For now, we'll use console.log(json)
to see the json
data.
Say That Again?
Let's go through that again: 1. We make the fetch
request. 2. We pass in the NYT url
. 3. We create a promise .then
that returns a response object called result
. 4. The promise asynchronously returns a function that converts the result into usable json
format - result.json()
is that function call. 5. We create a second promise that has a function that takes in the json
object. 6. We log the json
object for now.
Last updated