Skip to content

The Whole Picture

You have all the pieces now. Arrow functions, promises, fetch, then, catch, finally. Let's put them together and read a complete fetch call line by line.


A complete fetch call, annotated

fetch("/patients")                         // 1. send a GET request, get a promise back
  .then(response => response.json())       // 2. when response arrives, parse the JSON (also a promise)
  .then(patients => {                      // 3. when parsing is done, use the data
    let tbody = document.getElementById("patient-rows")
    let html = ""
    for (let patient of patients) {
      html += "<tr><td>" + patient.name + "</td><td>" + patient.age + "</td></tr>"
    }
    tbody.innerHTML = html
  })
  .catch(error => {                        // 4. if anything above failed, run this
    console.log("Error:", error)
  })
  .finally(() => {                         // 5. always runs - success or failure
    console.log("Request complete")
  })

Line 1 - fetch() sends the request and returns a promise immediately. The request is now travelling to the server.

Line 2 - When the response arrives, .then() runs. response.json() opens the envelope and returns another promise.

Line 3 - When the JSON is parsed, the second .then() runs. patients is now a JavaScript array you can loop through.

Line 4 - If anything in lines 1-3 goes wrong, .catch() runs instead. The lines above it are skipped.

Line 5 - .finally() always runs at the end, no matter what happened above.


Old style vs arrow style

These are identical. The arrow version is what you will see most often:

// old style
fetch("/patients")
  .then(function(response) {
    return response.json()
  })
  .then(function(patients) {
    console.log(patients)
  })
  .catch(function(error) {
    console.log(error)
  })

// arrow style
fetch("/patients")
  .then(response => response.json())
  .then(patients => console.log(patients))
  .catch(error => console.log(error))

The mental model

fetch(url)
  |
  +--> promise pending (request is travelling)
  |
  +--> promise fulfilled (response arrived)
        |
        +--> .then() #1 - parse JSON, returns new promise
              |
              +--> .then() #2 - use the data
  |
  +--> promise rejected (something went wrong)
        |
        +--> .catch() - handle the error

.finally() - always runs after everything above

Challenge

Write a complete fetch call from scratch - no copy-paste. Fetch from https://jsonplaceholder.typicode.com/posts using arrow functions throughout. Log the title of the first post. Include .catch() and .finally().


← Then, Catch and Finally    Next: Exercises →