Promises in Code

To see more general explanations of promises: Promises and Deferreds - How I Stared To Like Them

At a basic level what Promises do is the same thing as passing a callback to a function.

function myFunc(callback){...}  

var promise = myFunc();

But it is easy to get too many callbacks (if you work without promises), you need at least two, one for error and one for success. Functions need some arguments and you end up with a monster like:

myUgly(success, error, param1, param2, param3)  

or move to a config object:

myBetter({success: success, error: error});  

When I want to add another success function it gets uglier:

myBetter({successes: [success1, success2], error: error});  

The same functionality with promises will be probably more verbose but I think this is a good thing. The code below is much more maintainable and extensible:

var promise = myPrecious({param1, param2, param3});  

This two code examples may may look very similar to you but in my opinion second one is much more elegant, clean and obvious about what is happening.

It gets even better when you think about waiting for a couple of things to happen.
The easiest solution would be something like this underscore after:

var renderNotes = _.after(notes.length, render);  
_.each(notes, function(note) {
note.asyncSave({success: renderNotes});

What it's doing is just storing a variable in a closure and counting invocations of the function. With an underscore it's hidden behind a nice abstraction but for me it looks like a hack.

var runs = 10;  
function afterAll(){
if(runs-- > 0) return;
//do something useful

Now look at similar code but with promises (from Q.js):

//notes is array of promises  



For jQuery this will look similar:

var promise1 = $.ajax("/myServerScript1");  
var promise2 = $.ajax("/myServerScript2");

$.when(promise1, promise2).done(function(response1, response2){
// Handle both responses

Code examples were not tested but some of them were copied from other sites so they may work. I've created them only for explanation purposes.

Share on Hacker News
Share on LinkedIn

← Home

Want to learn more?

Sign up to get a digest of my articles and interesting links via email every month.

* indicates required

Please select all the ways you would like to hear from Krzysztof Kula:

You can unsubscribe at any time by clicking the link in the footer of my emails.

I use Mailchimp as a marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.