DailyJS

Let's Make a Framework: Promises

Alex R. Young

Subscribe

@dailyjs

Facebook

Google+

tutorials frameworks lmaf documentation promises

Let's Make a Framework: Promises

Posted by Alex R. Young on .
Featured

tutorials frameworks lmaf documentation promises

Let's Make a Framework: Promises

Posted by Alex R. Young on .
*Let's Make a Framework* is an ongoing series about building a JavaScript framework from the ground up. These articles are tagged with [lmaf](http://dailyjs.com/tags.html#lmaf). The project we're creating is called [Turing](http://github.com/alexyoung/turing.js). Documentation is available at [turingjs.com](http://turingjs.com/).

Promises are something you may have used without realising it. jQuery
manages them using Deferred
Object
, and Dojo has
dojo.Deferred which is similar. There are also a growing number of Node modules that offer APIs
for working with asynchronous promises, some of which can work in
browsers as well.

It's easiest to understand promises with an example:

$.get('test').then(
  function() { alert('$.get succeeded'); },
  function() { alert('$.get failed!'); }
);

This is from jQuery's documentation. When the Ajax request succeeds, the
first callback will be run, else the second is run. The most important
thing is the Ajax method returns an object with a method called
then with this signature: then(fulfilledHandler,
errorHandler, progressHandler)
. It might not sound particularly
exciting, but it can lead to surprisingly readable and expressive code.

CommonJS

There is a CommonJS proposal for Promises, known as
Promises/A. It defines the then method, and also get and
call. These methods form what it calls an
"interactive-promise".

In an interactive-promise, the get(propertyName) method
will return a promise that requests the given property from the target
of the current promise. Meanwhile, call(functionName, arg1, arg2,
...)
will request to call the function from the target of the current promise and returns a promise to provide the resulting value.

Notice how this syntax is eminently chainable -- various levels of
asynchronous operations could be stacked and manipulated.

Practicality

While promises sound like a great way to interact with asynchronous
code, the practicality isn't immediately obvious in a web framework,
outside of Ajax calls. However, they can be used to build more advanced
functionality within the framework. People don't necessarily need to
fully understand promises to be able to take advantage of
\$.get('/url').then(function() { }). And promises seem like
a good way of modelling animation behaviour without adding a complex
library for animation scheduling.

Next

Next week I'll take a look at building promises in browser-friendly
JavaScript. If you're interested in reading more, take a look at: