promises promises

An introduction to Javascript Promises


WHAT?


A technique to  improve the readability of your asynchronous js code

What does that mean?




  1. a way to refactor your callbacks so that you don't get so much nesting
  2. a cleaner way to do error handling

You start off with


var user = login('vee');

var tweets = getTweetsFor(user);

display(tweets);

But That Blocks, so...


login('vee', function(user) {

   getTweetsFor(user, function(tweets) {

      display(tweets);

   } 

}

And what if something goes wrong?



  try {

      login('vee', function (user) {

           try {

               TwitterAPI.getTweetsFor(user, function() {

                    try {

                        display(tweets);

                    } catch (e) {

                        display("fail");

                    }

                } );

            } catch(e) {

                   display("fail");

            }

      });

  } catch (e) {

        display("fail");

  }

THe problem



Enter Promises...


login('vee').

   then(TwitterAPI.getTweetsFor ).

   then(display, 

              function(error) {

                  display("fail");

              });

Moar about promises


  • Thenables - do this, then do this, then do this...
  • Callback aggregation
  • Chaining <3
  • Reduced nesting
  • Badass error handling...

Error handling in async code


error handling 101


try { 

  (function() {

      throw "river"

   }()); 

} catch (e) { 

   console.log('cry me a ....' + e);

 }

Async error handling fail


try { 

   setTimeout(function() {

       throw "river";

   }, 1000);

} catch (e) { 

   console.log('cry me a ....' + e);  // or not

 }

error handlers in promises


  • Promises take a success callback and an error callback
  • If a promise is fulfilled then the success is handler is called
  • If a promise is rejected then the error handler is called
  • If there isn't an error handler, then the error bubbles up the promise chain

Promise error handling win!


login('vee').

   then(function (user) {

    TwitterAPI.getTweetsFor(user);

   }).

   then(function (tweets) {

        display(tweets);

   }, function(error) {

          display("fail");

   });

But nobody's perfect...




  • Hiding the async can be confusing - MAGIC
  • jQuery implemented it badly, so some implementations don't interop
  • Its not a standard yet

libraries


Q
when.j s
rsvp.js

dojo
jQuery...

and our friend Angular :P


Alternatives

https://github.com/caolan/async



readme

https://github.com/promises-aplus

You're Missing The Point Of Promises:
https://gist.github.com/domenic/3889970