Asynchronous: Chaining promises

A promise can be returned from a then() method of a promise.

You can then call its then() method, creating a chain of promises.

I think the best way to explain this concept is to use fetch(), a JavaScript feature we’ll introduce later on in details during this masterclass.

In short, we use fetch() to get a resource from the network.

In this example, we call fetch() to get JSON from GitHub with my user details (try with yours) using this URL: https://api.github.com/users/flaviocopes

fetch('https://api.github.com/users/flaviocopes')

fetch() returns a promise which resolves to a Response object. When we got that, we need to call its json() method to get the body of the response:

fetch('https://api.github.com/users/flaviocopes')
  .then(response => response.json())

This in turn returns a promise, so we can add another .then() with a callback function that is called when the JSON processing has finished, with the job of writing the data we got to the console:

fetch('https://api.github.com/users/flaviocopes')
  .then(response => response.json())
  .then(data => {
    console.log('User data', data)
  })

For comparison, with async functions we’d write the above code in this way:

const getData = async () => {
  const response = await fetch('https://api.github.com/users/flaviocopes')
  const data = await response.json()
  console.log('User data', data)
}

getData()

Lessons in this unit:

0: Introduction
1: Callbacks
2: Timers
3: Promises
4: Async functions
5: ▶︎ Chaining promises
6: Orchestrating promises
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!