Fetch() API – JavaScript

Before you study this topic make sure to understand: PromisesJSON 

Video Tutorial Resources: Link1Link2 – Link3

Examples using the “FETCH() API

This example is from this: Video-Link, in this example we:

  • create a constant named “root” and load it with a Free API-Url 
  • Invoke fetch( root, { method: “GET” } ) with the parameters “root”, and the method: “GET”
  • Use “.then” passing an anonymous function that receives the response when the promise is fulfill
  • This anonymous uses the proto method “.json” to modify the data, and return it.
  • Use “.then” by chaining, it receives the data and prints it.

In the next example we do the same but we add “.catch()” so we can catch if the API do not provide a 200 response:

Another example:

One practice exercise:

Here we are getting the Title: “Harry Potter 1 and the Philosopher’s Stone” from the API and rend it to the DOM  <div id=”div1″>

 

.

 



Copyright 2017. All rights reserved.

Posted July 6, 2017 by Edmundo in category "JS