Object JavaScript – Asynchronous Programming Using Promises

10063_580983808600819_401360548_nPromises are a way that lets us write asynchronous code that is almost as easy to write as if it was synchronous.

You need promises as soon as you do anything that involves an asynchronous API. It also does not take very long before writing promise chains for sequential asynchronous operations becomes second nature.

A Promise is an object that basically represents a process that is or will take place at some point in time, but allows you to register callbacks to it for when the process gets terminated or completed.

Instead of blocking and waiting for the long-running computation to complete, a promise returns an object which represents the promised result.

In this post, you will get an introduction into JavaScript promises.

The CommonJS Promise/A proposal provides a beginning point to talk about Promises. Several JavaScript libraries implement promises, sometime with some nuances. This post provides a basic overview. In later posts, you will learn about how to implement promises for particular libraries.

What is a Promise?

In a github gist, Domenic Denicola described it this way:

The point of promises is to give us back functional composition and error bubbling in the async world.

A promise is really nothing more than a code construct. A promise is simply an object representing a value that might be available at some point in the future, or might already be available.

An example of this might be making a request to a third-party system where network latency is uncertain. Instead of blocking the entire application while waiting, the application is free to do other things until the value is needed.

In a synchronous world your code would look like this:

asyncCall(data,function(response){
    // You have response from your asynchronous call here.
}, function(err){
    // if the async call fails, the error callback is invoked
});

With promises, your code looks like this:

var promise = asyncCall(data);
promise.done(function(response){
    // You have response from your asynchronous call here.
}).fail(function(err){
    // if the async call fails, you have the error response here. });

Chaining Promises

A promise implements a method for registering callbacks for state change notifications, commonly named the then method. In the following example, searchTwitter returns a promise that receives the then method which calls a function filterResults once the searchTwitter returns.

var results = searchTwitter(term).then(filterResults);
displayResults(results);

If a function cannot return a value or throw an exception without blocking, it can return a promise instead.

Three States

A promise represents the return value or the thrown exception that the function may eventually provide. At any moment in time, promises can be in one of three states: unfulfilled, resolved or rejected.

The ‘then’ method accepts two parameters: one for when the promise was resolved, another for when the promise was rejected.

var promise = searchTwitter(term); // searchTwitter returns a promise 
promise.then( function( futureValue ) {
     /* we got a value */
   } , function() {
      /* something went wrong */
    } );

In another example, you can have an object save itself. In the traditional case, it might looks like the following:

object.save({ key: value }, {
   success: function(object) {
     // the object was saved.
   },
    error: function(object, error) {
     // saving the object failed.
   }
});

With promises, the save looks like this:

object.save({ key: value }).then(

   function(object) {     // the object was saved.
   },
   function(error) {
     // saving the object failed.
   });

Calling promise.then(func) returns a new promise, which is not fulfilled until func has completed.

When You Need Many Async Operations

Sometimes you need to have several results returned before your application can continue.

Where this is the case, a method called ‘when’ exists, which can be used to perform some action once all the promises have been fully fulfilled.

The following pseudo-code shows who a when function might be implemented.

when(
   promise1,
   promise2, ... ).then(function( futureValue1, futureValue2, ... ) {
   /* all promises have completed and are resolved */
});

Other Benefits

Promises based implementations is how they are helpful in attaching multiple callbacks for an async operation. With Promises, you can attach listeners to an async operation via done even after the async call has completed. If attached after completion, that callback is immediately invoked with the response.

var p = async(data);
p.done(function(response){
   // do task 1 });
p.done(function(response){
   // do task 2 });

Implementation of Promises

Promises are provided in many JavaScript toolkits, including

In addition several standalone libraries provide promises without dependencies on other frameworks:

References

Advertisements

One comment

  1. Pingback: Object JavaScript – Promises for Asynchronous Operations Using jQuery | DevDays®