Two coffee cups

I wanted to learn about Promises.

So I created an app to dive into this topic. Hopefully I can help you understand and encourage you to try for yourself!

What is a Promise?

It's an object that represents a future value. This allows for asynchronous methods to return values like they're synchronous. The asynchronous method returns a promise of having a value at some point in the future.

A Promise can have three states:

  1. pending: Neither fulfilled or rejected; usually associated with its initial state
  2. fulfilled: The promise has completed successfully
  3. rejected: The promise has been rejected

Why Did I Choose to Use Promises?

In my app, I make five API calls. I wanted to wait until all five were completed before rendering the data onto the page. My strategy was to create a new promise each time I called the API. Then I stored each promise into an array and once resolved, used Handlebars to render data onto the page (stay tuned for an upcoming blog post on templating).

For the next two sections, I'll display snippets of code and then provide the Codepen at the end.

Creating the Promise

For the API call, I'll be retrieving weather data for 5 cities.

cities : [
  "San_Francisco",
  "Miami",
  "New_Orleans",
  "Chicago",
  "New_York_City"
];

Next, I create an array that holds each promise returned from calling the API function.

var cityData = cities.map(apiCall());

Next, create the function to call the API. Notice that a new Promise is created and returned.

var apiCall = function (city) {

  // Create new promise
  var promise = new Promise (function (resolve, reject) {

  var xhr = new XMLHttpRequest();
  xhr.open("GET", apiUrl);

  xhr.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
      var responseArray = JSON.parse(this.responseText);

      // When the promise resolves, return the response 
      resolve(responseArray);
    }
  };

  xhr.send();
  });

  // Return the promise to the array, cityData
  return promise;
};

Promise Success

A Promise.all will be used to make sure all five requests are resolved and rendered all at once through a then() function. We'll also include a catch() function that will be used to display a message to handle a promise rejection.

Remember the cityData array from above? We'll use it here:

Promise.all(cityData)
  .then(function(value) {
    // Render data onto page
  })
  .catch(function() {
    console.log("An error has occurred in retrieving the data from the API call.")
  });

The Final Product

You can take a look at my app on Codepen and Github.


Now it's your turn to give Promises a go!