First up, I think they are all asynchronous techniques. Async is all the rage, I started hearing lots about it when news about node.js started hitting the blogs. There was a bit of it back when AJAX was a hot buzzword, but it was limited to handling of HTTP responses then (which pretty much had to be async—delaying your whole program to fetch a resource over the net would be too slow). Now we’re using async all over the place!
My layman’s understanding is that a good use of async removes bottlenecks. Say you need to read a file or fetch data from a server or spin off a complex computation? Have that run separately and let your program keep running. You’ll pick that up when it’s ready. In synchronous coding, your code would be stuck waiting for everything to execute in order. That’s my understand of async coding. And I think callbacks, defer and promises are async patterns.
Callbacks I know about. A function that ‘calls back’ takes another function as an argument. It will call that function at the appropriate time (when it finishes what it was doing)—for example: when a HTTP response is received, when an event occurs, when an animation completes. jQuery has plenty of callbacks.
Defer I’m not sure about. I know there is a defer attribute in html for script elements, which indicates the browser can delay executing the script. I have a feeling there might be another concept called defer which is a programming pattern though.
I’ll be back to update this article after that!
[Update: ok, it looks like promises are a pattern for callbacks which make the code easier to read. A promise returns an object immediately. That object has methods to register callbacks. ‘Then’ and ‘When’ seem to be conventions for the method names. That reminds me of behaviour-driven development, but has nothing to do with it. Well, maybe I have seen the promise pattern in some BDD code. Aha! Chainable callbacks. It seems a promise is an alternative to throwing exceptions too, nifty! I’ve added some references to the end of this post.]
[Update 2: I can’t find much extra detail on defer, unless they were asking me about $.Deferred in jQuery, which looks to be a sort of promise factory.]
- You’re Missing the Point of Promises (this article is great!)
- ASYNCH JS: THE POWER OF $.DEFERRED