Online Since 1995

Adventures in Windows 8: Making Your Own Promise

Tags: Adventures in Windows 8, WinJS, Promise, JavaScript

On Friday, I wrote about the WinJS.xhr object and the notion of a Promise in JavaScript.

Today, I’m going to show what it takes to create your own promise.

First, let’s take a look at this function below:

 

   1:      function loadDetails(areaCode) {
   2:   
   3:          var areaCodeInfoUri = baseUri + areaCode;
   4:   
   5:          var promise = new WinJS.Promise(function (complete) {
   6:   
   7:              WinJS.xhr({ url: areaCodeInfoUri }).done(
   8:              function (xhr) {
   9:   
  10:                  var rawHtml = xhr.responseText;
  11:   
  12:                  areaCodeDetails = parseRawHtml(rawHtml);
  13:   
  14:                  complete(areaCodeDetails);
  15:   
  16:              });
  17:   
  18:          });
  19:   
  20:          return promise;
  21:   
  22:      }

 

What the Code Does

The code makes a call out to a third party site, pulls back from HTML, and then hands that' off to a screen scraping method.

The call to the third party site requires an asynchronous call on line 7. The code inside the done block doesn’t get executed until the network request had completed.

What I really need from this function is a areaCodeDetails object filled with metadata about an area code.

Take a closer look, though, what does the function actually return?

The answer lies on line 20: the function returns a Promise object.

Promises, Promises

The promise variable get instantiated on line 5, where I pass an anonymous function into its constructor. (This sort of structure makes JavaScript code succinct and, at times, harder to read for C# types like me. Once you get used to it, however, it’s a tidy little way to define functions.)

Notice what I pass into the Promise constructor method: a function with a parameter called complete. The first parameter here will be the reference to the function that signals to the runtime that the operation has completed.

I could call this parameter anything and if you read this post about the innards of the WinJS.xhr object, they chose to call this parameter c,

Fulfilling the Promise

On line 14, I make a call to the complete method. This is the line that actually “fulfills” the promise and signals its completion.

You may also notice that I pass an areaCodeDetails object along to it.

I do that make the results of my screen scrape available to the code that’s awaiting the result of my function.

Check out the code below where I make the call to the getDetails function and use the data from it to populate my UI.

 

            var details = areaCodeDetails.getDetails(areaCode).then(function (detail) {

                serviceDateElement.innerText.serviceDate = detail.serviceDate;

            });
Add a Comment