Callback nesting turning your JavaScript into a tangled web of messy
madness? Still polling?
If you're a fan of jQuery or Underscore, you might also enjoy Futures:
http://github.com/coolaj86/futures
Hey,
I just finished the core of this library and this is my pitch for it. Take a
look, give me some feedback. Fork it, join the list, whatever.
I developed it to enable me to to embrace the asynchronous and event-driven
nature of JS without getting tangled up and lost in callbacks or polling.
With FuturesJS you can:
- create Crockford-style `promise`s (futures) - a more formal way to
handle callbacks.
- `join` multiple callbacks - if you have several `xhr`s (or user
`event`s) that must complete before continuing in the program flow.
- create `subscription`s - a `promise` that is issued each time a
function is called (or an event happens)
- `synchronize` subscriptions - much like `join`ing a promise
- `sequence` asynchronous events
- `chainify` an asynchronous model
- non-blocking `whilst` loops
Asynchronous method queueing was the biggest goal, which I just added
yesterday. It allows you to do stuff like this:
Contacts.all(params).randomize().limit(10).display();
Contacts.one(id, params).display();
Where the implementation looks something like this:
var Contacts = Futures.chainify({
// Providers must be promisables
all: function(params) {
var p = Futures.promise();
$.ajaxSetup({ error: p.smash });
$.getJSON('http://graph.facebook.com/me/friends', params,
p.fulfill);
$.ajaxSetup({ error: undefined });
return p.passable();
},
one: function(id, params) {
var p = Futures.promise();
$.ajaxSetup({ error: p.smash });
$.getJSON('http://graph.facebook.com/' + id, params, p.fulfill);
$.ajaxSetup({ error: undefined });
return p.passable();
}
},{
// Consumers will be called in synchronous order
// with the `lastResult` of the previous provider or consumer.
// They should return either lastResult or a promise
randomize: function(data, params) {
data.sort(function(){ return Math.round(Math.random())-0.5); //
Underscore.js
return Futures.promise(data); // Promise rename to `immediate`
},
limit: function(data, n, params) {
data = data.first(n);
return Futures.promise(data);
},
display: function(data, params) {
$('#friend-area').render(directive, data); // jQuery+PURE
// always return the data, even if you don't modify it!
// otherwise your results could be unexpected
return data;
}
});
If you're not familiar with Crockford-style promises the p.fulfill, p.smash,
p.when can be clarified a little bit here:
http://coolaj86.github.com/futures/
or by watching Crockford's lecture, Act III
http://yuiblog.com/crockford/
I hope that was understandable enough and useful.
AJ ONeal