JS-151-API
  • JavaScript Library
  • 02-DOM-Manipulation
    • Overview
    • DOM Explained
    • Example Setup
    • Selecting Elements
    • Events
    • Complete Example
  • 03-API Fundamentals
    • 0-Getting Started
      • Welcome
    • 1-Intro-To-APIs
      • Intro
      • Client
      • Requests
      • JSON
      • API Endpoints
      • Server
      • Response
      • Statelessness
      • REST
    • 2-Asynchronous-Programming
      • Intro
      • Callbacks
      • Promises
      • Promises Continued
      • Chaining Promises
    • 3-Fetch
      • Fetch Intro
      • Star Wars
        • Star Wars API
        • Star Wars Setup
        • Star Wars JS
      • Random Photo
        • Unsplash
        • Unsplash Setup
        • Unsplash JS
    • 4-Apps
      • 01-New York Times
        • 00-App Intro
        • 01-HTML/CSS/API Key
        • 02-Variables
        • 03-Event Listeners
        • 04-fetchResults
          • 01-fetchResults()
          • 02-preventDefault()
          • 03-fetch() method
          • 04-Dates
        • 05-displayResults
          • 01-Logging JSON
          • 02-Working with JSON
          • 03-Link Display
          • 04-Results Navigation
          • 05-Results Update
          • 06-Keywords
          • 07-Images
        • 06-Pagination
          • 01-Pagination Intro
          • 02-Pagination Functions
        • 07-Next Steps
      • 02-YouTube
        • html
        • youtube.css
        • youtube.js
      • 03-GoogleMaps
        • Setup
        • HTML and CSS files
        • API Key
        • JS Setup
        • Adding Your Location
        • Listeners
        • Custom Options
Powered by GitBook
On this page
  1. 03-API Fundamentals
  2. 2-Asynchronous-Programming

Chaining Promises

Promises can be stacked on top of each other, or chained. Let's say you promise your friend you'll come to his house and play with the toys you get for Christmas.

We'll write this new promise a bit differently:

// 2nd promise
var playDate = function (gift) {
    return new Promise(
        function (resolve, reject) {
            var message = "Salutations fellow child I enjoy interacting with! I notice you received a posable plastic Batman figurine during the Yultide season. What do you think of my new " + gift.brand + ' ' + gift.item + '?';

            resolve(message); 
        }
    );
};
  • Did you notice reject wasn't called? Turns out it's optional!

  • We can refactor this example using Promise.resolve.

    // 2nd promise
    var playDate = function (gift) {
      var message = "Salutations, fellow child I enjoy interacting with! I notice you received a posable plastic Batman figurine during the Yultide season. What do you think of my new " + gift.brand + ' ' + gift.item + '?';
    
      return Promise.resolve(message);
    };

    Now that we have a second promise, let's chain the two together. Please note you can only start the playDate promise after the iCanHasGift promise.

// Promise call
var checkTwice = function () {
    iCanHasGift
    .then(playDate) // chain here
    .then(function (fulfilled) {
        console.log(fulfilled);
        // output: "Salutations fellow child I enjoy interacting with! I notice you received a posable plastic Batman figurine during the Yultide season. What do you think of my new HasMattelbro Turbo-Man action figure?"
    })
    .catch(function (error) {
        // all I got was a lump of coal :(
        console.log(error)
        // output: "You've made Santa's naughty list; enjoy your coal!"
    });
};

checkTwice();

Promises Summary

Promises for actions that will take an unknown amount of time that we want to react to. So some common examples: images being loaded, API calls, the page fully loading, calling a complex function, etc. The key, is that since JavaScript is a single threaded language, we want to be able to do things constantly, and don't want to be stuck waiting. Promises help us avoid waiting around for something to happen before we do anything else. So instead of just waiting forever for my info to come back from my API call, I can do everything else I need to do and then react to the info I get back when it eventually resolves.

When you see .then think promise!

We'll see a lot of promises when dealing with APIs! Because our API calls can take an unknown amount of time pending the internet, how well the API is written, etc. We always make API calls with promises when possible, so that we can do other things while we wait!

Promise Analogies (again):

  • buying concert tickets 4 months out. doing other things while waiting for the concert. getting what you were promised (a concert) 4 months later, and reacting to it (having a great time); or not getting what you were promised, and having to react to that (sadness)

  • applying to a job. doing other things while waiting to hear back like applying for more jobs. reacting to either the acceptance (preparing for a new job, giving 2 weeks, excitement, etc.), or the rejection (being sad, continuing to apply to other places).

PreviousPromises ContinuedNext3-Fetch

Last updated 7 years ago