Javascript Promises – A better way to complete your async operations

Promises, Promises, Promises…

If you are writing javascript regularly, you are probably already using callback functions. In complex Javascript applications callbacks can become deeply nested, and difficult to keep track of. This becomes even harder when you want to wait for multiple callbacks to finish executing, or if one of those callbacks throws an error while completing it’s task. One thing I personally dislike is seeing deeply nested functions due to callbacks waiting for callbacks.

If you haven’t seen these problems yourself, or for further reading on issues with callbacks check this out :

Callback Hell

Promises are an abstraction to help you write asynchronous code in a way that resembles synchronous code and is much easier to follow !

The promise standard defines a promise like this :

A promise represents the eventual result of an asynchronous operation.

Simpler version :

A promise represents an operation that hasn’t completed yet, but is expected in the future.

Pros and Cons of Promises

 Pros

  • Makes your async code more readable !
  • Part of the ECMAScript 2015 (ES6) standard – native browser support !
  • Waiting for multiple Async operations is simple.
  • Easily chain multiple Async functions.
  • Lots of great frameworks that provide seamless shims for older browsers.
  • DRY error handling
  • Functional approach to handling Async
  • Fast, in fact just as fast as callbacks

Cons

  • Higher learning curve
  • Can be used to create bad code
  • Errors get swallowed if not handled correctly
  • Not supported in older browsers
    • Requires a library to shim
  • Integrating with 3rd party frameworks that use the callback pattern might require more code to integrate with an existing promise chain.

Let’s see a Promise in action

You will probably run across a jQuery ajax request like this at some point in your development adventures:


var jqxhr = $.ajax( "http://hipsterJesus.com/api/" )
 .done(function() {
     alert( "success" );
 })
 .fail(function() {
     alert( "error" );
 })
 .always(function() {
     alert( "complete" ); 
 });

Now with 100% more Promise ! (using bluebird.js)

Promise.resolve($.ajax("http://hipsterJesus.com/api/"))
 .then(function(ajaxResult){
     alert( "success and complete!" ); 
 })
 .catch(function(error){
     alert( "error" );
 });

This is a simple example purely to show you the syntactical differences between promises and callbacks.

 We can go deeper…

Okay that previous example reads a little more cleanly than your standard ajax call, but that probably hasn’t whirled you into a promise frenzy yet.
What about making several async calls and then waiting for the result ?

Promise.join(
    Promise.resolve($.ajax("http://hipsterJesus.com/api/data")), 
    Promise.resolve($.ajax("http://hipsterJesus.com/api/People/1")), 
    Promise.resolve($.ajax("http://hipsterJesus.com/api/CatMemes")),

    function(dataResult, peopleResult, catMemesResult) {
        console.log(dataResult);
        console.log(peopleResult);
        console.log(catMemesResult);
    }
); 

Beautiful Meme
Asynchronous code is hard to write, and this is “stupid simple“.

Join() is a bluebird function that will take any number of promises as arguments, and expects the last argument  to be a the function to execute all the promises are complete. I really like the simplicity of writing asynchronous code like this.

Wrapping Up

A “promise” is an object or function with a then method whose behavior conforms to this specification.There are a lot of really cool benefits to working with promises, however like any pattern they can be problematic when written carelessly.I think most developers are making ajax calls to get data pretty often, so I thought the examples would make it easy to see how using promises can enhance your existing workflow.

At the end of the day promises and callbacks are two different approach for accomplishing the same goal. Each approach has some indisputable benefits, and neither is correct for every developer.

To be continued…

This is an introductory article on Javascript promises that hopefully gets your brain thinking about all the lines of code you could avoid writing with promises. I’ll be digging into debugging & advanced promise techniques in my next articles.

All my examples have were written using bluebird.js, which is a great library for working with Promises.

Further Reading :

Write better javascript with promises

You’re missing the point of promises

This one has a really good performance breakdown of popular promise frameworks : Why I am switching to promises

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s