I'm learning coffeescript and using it with node.js, building a basic rest api on express.js.
I'm beginning to realize that my code gets covered with multiple layers of callbacks. Some googling showed me that there are some alternatives like promises, futures and generators.
Look at async.js ( https://github.com/caolan/async ) It doesn't introduce new concepts, but allows you to streamline callback soup into something more manageable and readable. For example instead of
foo(data, (err, result) ->
bar( result, (err, omgimtired) ->
foobar(omgimtired, (err....) ->
...
)
)
)
You can just use async.waterfall and feed it a list of functions to call one after another.
Promises are quite simple (if you manage to wrap your mind around them). They describe an object which is the result of a particular operation. Imagine that you return objects from all your functions, which represent results. Now imagine that every result has a function (then(...)) which is passed a callback for 'successful' completion and a callback for the unsuccessful one. Easy, right? The only thing which makes promises special is that this callback may return another promise, which should be fulfilled first for the "enclosing" promise to be fulfilled. And so on. You just replace a sequence of callbacks with the chain of the .then(...) calls.
Parse.User.logIn("user", "pass", {
success: function(user) {
query.find({
success: function(results) {
results[0].save({ key: value }, {
success: function(result) {
// the object was saved.
}
});
}
});
}
});
versus
Parse.User.logIn("user", "pass").then(function(user) {
return query.find();
}).then(function(results) {
return results[0].save({ key: value });
}).then(function(result) {
// the object was saved.
});
From http://blog.parse.com/2013/01/29/whats-so-great-about-javascript-promises/
Drink this Kool-Aid http://www.slideshare.net/domenicdenicola/callbacks-promises-and-coroutines-oh-my-the-evolution-of-asynchronicity-in-javascript from the quite thorough answer on the similar topic What are the differences between Deferred, Promise and Future in Javascript?