Nested callbacks get really cumbersome after a while. Let's see some alternatives for a better Future of JS.
I Promise it will make your js code nicer.
Evented IO + CPS • Processes happens as events happens – Waiting for a result is not feasible • Continuing the process in the future – Passing it to future processes
Working implementation of Future • Async I/O + lack of threads makes it really complicated to use while loops in Javascript with background processes http://code.activestate.com/recipes/ 84317/
Promises • They are similar to Futures, in the sense of deferring execution. • The interface allows you to create utility functions to combine and chain multiple promises • (Shhhh! Promises are monads.)
JQuery 1.5 ajax object var req = $.get('foo.htm');! ! req.done(function(response) {! // do something with the response! });! ! req.fail(function() {! // do something if the request failed! });! ! var lis = $(“li”);! req.done(function(response) {! // do more stuff with response and lis! })!
Javascript community current state • Node introduced the default api of: func(args…,callback(err,arrgs…))! ! • Some libraries are handling the implementations of Promises • They got into an agreement called Promises/ A+ – http://promises-aplus.github.io/promises-spec/
Promises/A+
• General – A promise represents a value that may not be available yet. The primary method for interacting with a promise is its then method.
Some context on Promises utilities • We are going to show some code use the Q library https://github.com/kriskowal/q • Q.nfbind :: (err -> result -> ()) -> Promise result! • Q.all :: [Promise] -> Promise [Promise]! • Q.spread :: [Promise] -> Promise args… -> Promise! • This is not the exactly type signature, nor Haskell syntax, it is just similar!
Things I think it is important to say • Expose api’s that uses the community style guide to maximize integration – Expose func(args…, callback(err, arrgs…))! • Use Promises internally to make future data interaction and flow more explicit • Use callbacks when it makes sense (ie: click events…) • Everything in excess is bad • Try more functional approaches (: