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){...}
myFunc(alert);
var promise = myFunc();
promise.then(alert);
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});
promise.when(success1);
promise.when(success2);
promise.when(success3);
promise.fail(error);
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
}
ajax1(afterAll);
ajax2(afterAll);
...
Now look at similar code but with promises (from
Q.js):
//notes is array of promises
Q.all(notes).when(afterAll);
jQuery
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.
Comments
Post a Comment
Comments: