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
  • An Example
  • States of Promise
  • Creating a Promise
  • Consuming Promises
  1. 03-API Fundamentals
  2. 2-Asynchronous-Programming

Promises

MDN definition of a Promises is:

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Essentially, a Promise is code that is on it's way after it finishes running somewhere else. This is a key idea of understanding how asynchronous programming works within JavaScript.

An Example

We'll use this example throughout our discussion on promises:

Remember back to the good old days. If you were a good, well-behaved child that did your chores and stuff, then you were basically promised a gift from Santa.

As we all know, you can't really slack off because Santa is always watching... Yes, even when you are asleep. You won't know if you've been good enough until December 25 (or whenever you celebrate) and sit down to tear off the wrapping paper or look in your stocking. Until December 25th, you do lots of other things, you don't just sit there and wait to see what Santa brings.

There's really only two possible outcomes that you'll find: 1. You've been good enough to earn the gift promised from Old Kris Kringle, the King of Jingling. 2. You've made Father Christmas's naughty list and end up with coal.

Some other ways to think about promises are:

  • when you buy a ticket for something, you're basically promised that you'll get to see whatever that show is. For example, if I buy a Panic! at the Disco ticket 4 months before they play, I'm eventually just waiting to actually see the concert. While I'm waiting I can do other things!

  • Similarly, if I apply for a job, I can get accepted or rejected, but in the mean time, while I'm waiting to hear back, I don't just sit there and do absolutely nothing, I can do whatever else I want. Then when I get a response, I can decide what to do with it!

States of Promise

Promises, including the example above, have 3 states: 1. Pending - You have to wait until December 25 to receive your gift and find out whether you are naughty or nice. 2. Resolved - You've been a good little boy/girl and get that super awesome toy from Santa that you asked for. 3. Rejected - That super awesome toy of your dreams isn't waiting under the tree. You've been a mischievous, disobedient little brat and get what you deserve: a lump of coal.

Creating a Promise

Here's what our example looks like in JavaScript:

// Boolean declaration 
var amIGood = false;

// Promise 
var iCanHasGift = new Promise(
    function (resolve, reject) {
        if (amIGood) {
            var gift = {
                brand: 'HasMattelbro',
                item: 'Turbo-Man action figure'
            };
            resolve(gift); // fulfilled 
        } else {
            var naughty = "You've made Santa's naughty list; enjoy your coal!";
            reject(naughty); // rejected
        }
    }
);

Let's look a bit closer at a few things

  • amIGood - A Boolean variable to define whether you are naughty or nice.

  • iCanHasGift - The promise itself.

  • resolve(gift) - You made the nice list and received a Turbo-Man figure. The promise is resolved!

  • reject(naughty) - Your poor behavior has landed you on the naughty list. The promise is rejected. Don't forget your coal!

Here's the proper syntax for a promise:

new Promise(/* executor */ function (resolve, reject) {...} );

Consuming Promises

Let's consume our promise.

// Promise call 
var checkTwice = function () {
    iCanHasGift
        .then(function (fulfilled) {
            // nice list = gift
            console.log(fulfilled);
        // output: { brand: 'HasMattelbro', item: 'Turbo-Man action figure'} 
        })
        .catch(function (error) {
            // naughty list = coal
            console.log(error);
        // output: "You've made Santa's naughty list; enjoy your coal!"
        });
};

checkTwice();
  • checkTwice - function that consumes the promise iCanHasGift

  • .then - used with function(fulfilled) {...} if promise is resolved.

  • .catch - used with function(error){...} if promise is rejected.

  • fulfilled - the value passed in resolve(). In our case, gift is the fulfilled value.

  • error - the value passed in reject(). In our case, naughty is the error value.

That's a good start. Next up, we'll learn about chaining promises.

PreviousCallbacksNextPromises Continued

Last updated 7 years ago

This example comes from the , which goes more in-depth with what that executor comment means.

MDN Docs