 All right, I'm a bit oversized for this podium. Sorry, let me know if I drop volume at any point. So I'm going to go ahead and call this kind of technical. There's a breakout session right now that has to do with debugging mobile devices with ShadowJS, if you're also interested in that. This is your one chance to escape. There's one typo in my presentation. Please email me afterwards, and I'll get you something special. And also, there is some code here, just in case it doesn't show up clearly on this projector. You can pull both an HTML and the keynote version of this presentation down from my GitHub, which is Alex McPherson. My name just smashed together. No creative handles there. Cool. So I'm going to talk about when to use deferreds. Here's the outline of the talk. Who am I? What am I doing here? A bit of history about jQuery deferreds, a walkthrough of what kind of methods are exposed on a deferred object. I'm going to present six problems, show you six solutions that can be solved really elegantly using deferreds, come up with a list of best practices, and then open it up for some Q&A afterwards. So important life-altering facts about Alex. This is really going to help us bond here. I use sublime text, too. I like the Railscast 2 color scheme. I prefer inconsolata for my font, comma last, not comma first. And I always, always include my semicolons. Hopefully I can make some friends this way. I'm from Boston. I now live in Boulder, Colorado. It's unfortunately on fire. Hopefully it's out by the time I get back. I work at a web consultancy called Quick Left. We help startups in the Boulder tech scene. I'm a front-end developer there. I also lead our training and apprenticeship programs, and I also teach a grad program at CU, teaching Ruby and Rails and JavaScript. My skill set, I used to work for big banks, code performance, IE6. I no longer do that, which is not bad. So now I work with one to three month startup projects. I get stuff done really quickly. Thick clients, web sockets, Backbone.js, that type of stuff, just so you know where I'm coming from. So deferred history. I can't really see what this lights. I'm curious, can you raise your hand if you've ever written code that leverages a deferred in some way? OK, cool. That's about a quarter of the room. This is great. No one else is going to know what I'm talking about or if I'm making any mistakes. That makes me feel pretty comfortable. Good. In late 2009, there were some requests on the feature tracker to add some extra hooks into dollar Ajax to attach new callbacks. This Frenchman named Julian, I'm not going to try his last name, steps up. Apparently, he goes into a cabin in the woods for three weeks, rewrites the entire guts of Ajax. I don't know if you've looked at that code, or at least how it used to be. It was pretty nasty. So that's a monumental task. He exposed a really clever internal API, and then it was recommended like, hey, why don't we make that public? So that was released only two months after it was suggested. It was a pretty cool feat to do that. It's based on a common JS proposal called promises slash a. Common JS is a suggestion bucket for the future of JavaScript. Based on means it's pretty much the way it was suggested. It's used internally in jQuery, in the Ajax, in the effects libraries, and we're going to figure out how we can use it. So if you haven't used a deferred before, if you're in that three quarters of the room that didn't raise your hand, I'm going to show you some of the methods here. What is a deferred? It's basically a state storage object. You create it like this. There's a constructor function. Then if you inspect DFD's state with the state method, it'll show pending as a string. Does that code show up OK? That looks pretty good. Great. So we have a deferred. It's state is pending. We made it like this. And then we can change its state to resolved by calling resolve on the deferred. We can also set its state to rejected by calling reject on the deferred. There are callbacks that you can attach to these state changes. So once you have a resolved deferred, you can attach an event to be fired when it changes to resolved by saying deferred.done. And then you pass it a function reference or an anonymous function. So when this deferred changes to done with a resolve call, it'll log out. This deferred state is now resolved. To attach it to the rejected state, you use the fail method. So when it fails, it'll log out that code. And then there's kind of a catch-all, which is always. So you might see this has a lot of parallels to the actual Ajax function. You have success, error, and completed. It's pretty much those functions you can think about in the same way, just different words for them. This is an abstraction out of Ajax, basically. So these are the ways to attach callbacks, always done and fail. To affect the state of a deferred, you can reject it. You can reject it with context. That's a typo. Sorry, reject and resolve do not take context first. They just take arguments. Resolve and resolve with. To check out its state to inspect the deferred, you just called dot state on it. I believe in 1.9 is rejected and is resolved, which returned Booleans is going to be removed. It may be 1.8. Either way, it's still in the code base, but you shouldn't be using it. There's a big nice flag on the docs page to tell you not to use those. And then there are some utility helpers, pipe then and when, which help you join these together into some more meaningful structure in your code. So here are some examples. The first one is bundling Ajax calls. Our task at hand is to render a small sidebar with data from three different sources. You've probably had to do this before. I'm going to show you a couple of stabs at solving this without using deferreds to show you how bad it can get. So here's a junior developer writing the first Ajax call. And then they say, well, I get this success callback. I'll make another Ajax call. And then you get a success callback on that. And you say, I'll make another Ajax call. Don't do this. If you're laughing, you know why. That's good. You're losing the asynchronousity of Ajax. They're firing serially, which isn't something that you necessarily want. So you're losing time. That's bad. Here's maybe a more advanced attempt. We're going to have an array. And for all these different Ajax calls, we're going to push something onto that array to register that it's finished. And then we'll also check data calls. So here are three functions. And then check data calls, which is fired in every success, looks at the array, sees if it has all three values, and then maybe calls the render function. A bit better, these calls can be run in parallel. But still, that's a lot of lines of code. I had to shrink it to fit it on. Not good. So let's check out deferreds. We're going to write our get address function, which is our first of our three data calls. And the key here is that this is going to return a deferred-like object. Ajax doesn't actually return a deferred. It returns a JQXHR object that implements the promise methods, if you want to get technical. But we can call it a deferred for now. So it returns a deferred. We're going to implement the other two data calls in the same way. And then to tell when all three are done, it's a simple matter of using the when function. When bundles up multiple deferreds and returns one deferred that represents all of those. So you pass it three deferreds, which is the result of those functions. And then you can put a callback on the end of that. So this reads like English. I think it's quite pretty. When you get address and tweets and Facebook, then render the sidebar. It's pretty cool. A project manager could probably write this. I'm sorry if you're out there. So when returns one deferred to represent many. Pretty cool. Not many lines of code. The template pattern. I've tried to read the gang of four book. I don't know if you're familiar with that. I'm not going to say I finished reading it. But the template pattern is one of the easiest design patterns to understand. It's when you have multiple objects and classes that all implement the same methods. You don't care what they actually do, but you can interact with them in the same way. So our task is to make a single page app. Our main object is going to be pages. And some pages will need to fetch data before they get rendered. And other pages won't need data. So how are we going to deal with this? I'm going to skip over the junior dev examples. And so you write how to use deferreds in a cool way. So here's our about page. On its prototype, we have a knit function. What this does is it makes a data call. And it saves that deferred on the instance of the page. We have a second page, a contact page. This also has an init function. And for consistency's sake, to follow with this pattern, we're going to keep a deferred on the page object. But it's going to be a deferred that's immediately resolved. It doesn't actually do anything. What this consistency lets us do is, I'll collapse those for you, and it lets you write code like this. When you change the page, you pass it a page object. When that page is deferred, is done, then you render it. So the first time you come into the about page, which needs some data, it will make a data call, and it won't draw any HTML until it has its data. The second time you come back, that deferred has been saved on the object, and it's still done. So the done callback fires immediately. It immediately resolves itself. When you go to the contact page, that also has a deferred saved on it. The deferred is immediately resolved, so it immediately renders, and you don't have to wait for anything. Now, I mentioned that if you saw my comments quickly, I'm not comfortable going backwards here. We'll see how it goes. A deferred is not necessary here. Any non-deferred type is treated as an immediately resolved deferred. I just did this for consistency so that we can remember that we have to attach a deferred here. So that's pretty cool stuff. And then you can also inspect later. You can say page.def.done. Like, is it resolved? You can see what the state is. And this really helps smooth over navigation on single-page apps, which are becoming more and more popular. So any object that isn't a deferred can still be treated like one, and it'll get immediately resolved. Pretty cool stuff. All right, caching. Has anyone here written caching client side? I should see everyone's hand go up. Some kind of caching object. Cool. It's a common problem to have to solve, especially if you're doing mobile dev. You want to reduce the amount of data coming over the slow 3G networks. So in this case, our app uses a rate-limited API. We're going to say Twitter. Don't go over this rate. So limit your Ajax calls. We're going to make a tweet object that has a cache on it. The cache is going to be the keys will be user names in Twitter, and the values will be deferred objects. So here's a search function. It takes a username. And then it says, if I don't already have an entry for this username, make an Ajax call. In this case, getJSON. GetJSON is an Ajax call, so it returns a deferred. So you can see on line 9 that it sets to this cache, let's say, dot Alex McPherson equals the deferred that was generated when I got my tweets. And then return that deferred. So the interaction with this method is pretty simple. Tweets.search Alex McPherson. And then you can say, dot done, run some kind of function. In this case, we'll just take a look at the data that comes back. This makes a round trip to Twitter servers down the road. If we call it again, this does not make a round trip. This is the exact same method. The done function is attached to the same deferred, which is already resolved, so it resolves instantly. And any callbacks that are triggered by a done function get the exact same parameters as the first callback did. So you still get data. Sorry, that should say data.results. That's how Twitter gives you back your results. But you save a round trip. So it's a really clever way and only about 10 lines of code to make a pretty efficient caching mechanism. This doesn't work if the data changes. This is my recent timeline. So this might not be a totally effective use case, but you can figure out a good way to use it. Callbacks attached to deferreds always get the same arguments. Cool, pretty syntax. Some people say JavaScript isn't the prettiest language. I think it's pretty cool. And you can make it really eloquent. So the methods on the deferred object are already pretty cool. You can write things that look close to English. And you can extend that to your needs. So here's a quick quiz. Do you guys know which one of these is the correct signature for get timeout? Some of them treat timeout like two words in its camel case with the capital O. Some have time first. Some have function reference first. I always have to think about this for a second and look it up. The answer is D. Maybe that's my deficiency. But I prefer to wrap up set timeout in this kind of pretty syntax. So you can make a new function, dollar.wait. You pass it a duration. And internally, it uses a deferred, which set timeout will resolve after that duration that you passed in. This lets you write really pretty code that looks like this. Wait 1,000 milliseconds, then go make T. That's pretty cool. Prettier than you can usually do JavaScript in. Here's another task. We are going to wrap up an API. I'll keep using the Twitter API. So here's our search function that generates a deferred, and then it returns a promise. And then you can use it like this. My Twitter.search Alex McPherson done render tweets. We just saw this example. Something a little bit off topic I want to talk about is line six, where I return a promise. A deferred is this whole state object. And you can also resolve and reject its state. You can change its state. If you want to protect that, and you don't want to let anybody else mess with that state, you return a promise. A promise is a subset of that deferred object. All it exposes is the ability to attach additional callbacks to this deferred, but you can't resolve it or reject it. That's all that Ajax gives back. And Ajax resolves or rejects itself, right? The call comes back, and it either fires success or error. You can never say Ajax.resolve and finish it early because you don't have the data. So that's a good way to protect yourself in writing your own code, or if you're writing a library for reuse to only return promises. So again, my Twitter search, Alex, that sounds almost like English. I like that. So good syntax. You can also bundle them up. When I search for these two people, when both of those are done, do something with the results. You get a bit of a funny format of an object pass, but you still get the original data from each of those deferreds. So def one will be the search results for Alex McPherson. Def two will be my boss, Wookie Hangover. There's a funny story there. You have to ask him someday. But the data is still there, which is pretty cool. So the natural language syntax is already there, but you can extend it and make your code pretty cool. Also, always return promises. Generally, as a rule, unless you know that you need the full deferred. So number five, arbitrary events. Our task is to get some updates fired during a longer running process. Bear with me on this one. I'm going to admit it's a little bit of a contrived example. So we have this watcher deferred. That's going to hang out in the global scope. We're going to attach another kind of callback to it called a progress callback. In this case, you can read through the code, but the gist of it is what it does, is it fires a console logs when you're halfway up counting up to a number. Again, arbitrary. It's also going to have a done callback, saying that I'm done from a done handler. And now here's a method that's going to work with this deferred. It's called a slow counter. You pass it a starting number and a limit number, and it's slowly with a timeout will go up the number chain. Every time it runs, it's going to fire a notify event. Resolve fires done events, reject fires failed events, notify fires progress events. These match up pretty well. So we're going to send some data to that progress callback. If start is the limit, then we're going to resolve that deferred, and we're done. Otherwise, we're going to set a timeout and slowly count up these numbers. So what happens is when you run this function with 0 and 100, halfway through, it'll log out halfway done. And then when it's done, it'll say that I'm done from the done handler. So this is a bit of a contrived example, but there are some real-world places where this is useful. It's used in dollar animation and the HTML file upload API. You can also make server responses that you can work with to trigger this. But you'd have to make that work out of the box on your own. But it's pretty cool. I'm not really sure how much you could use it. I'm thinking there are some game dev applications. But cool stuff. Managing animations. This is our sixth task. So our task at hand is to implement a complex animation with tight tolerances. We have a crazy creative director that has this great vision of things sliding and disappearing. The built-in helper methods generate promises on their DOM nodes. That's a fancy way of saying that you can use deferreds to figure out when animations are done. So the built-in methods look like this. Fade in, fade out, hide, show, all these convenience ones. Little did you know, you can get some more granularity into figuring out how far along they are and when they're done. So we are going to make a function called complex remove. It's going to do some wild stuff. It's going to have a collector called defs. It's going to be an array of deferreds. Our two removals are on H1. After some random delay, it's going to fade out. And we're going to take all the divs, fade them in really quickly, wait a second, and then slide them out of the page. Again, this is kind of an arbitrary thing. But it's a complex animation. And because of the math.random, we don't know when it's going to finish. But we need to do something as soon as these are done and are animated, done animating, excuse me. So we now have an array of these deferreds that are being collected on defs. I'm going to return only one deferred. You can see I'm using when again here. When takes many deferreds and turns them into just one that represents the state of all the deferreds that it was passed. So only one thing is coming out of here. We have to use a funny syntax using apply here. When takes a comma separated list of deferreds, we have an array, so that's a pretty good use case for using apply, which takes an array of arguments. You don't necessarily need to pass in a context, that's why null is here. Some people pass in dollar sign, but when doesn't use a context, so it doesn't really matter. Point being, we get one deferred out of here. And then you can write some code like this. When the complex remove is finished, close the window. That's pretty simple. I can imagine about 100 different awful scenarios of spaghetti code that could manage this otherwise. So using deferreds to figure out when things are finished is a pretty powerful tool. It's really hard without deferreds. All right, here are some things I didn't even mention, but are still awesome. You can register multiple callbacks to the same deferred. So when you make an Ajax call, and you get one chance at that success handler, right? You can make that call other methods, but then you have one success handler that's in your dollar Ajax call that just gets longer and longer. It's not really pretty. So if you save a reference to that Ajax call, you can dot done as many callbacks as you need to fire when your Ajax call is finished. Same with dot fail and dot always. Post resolution binding, that sounds complicated. It's not really. If you save a reference to a deferred, var DFT equals my Ajax call or something like that. Let's say on the page load, that's fired. 10 minutes later, you can hook a callback to that, and you can say, oh, when that deferred is done, fire this function. The deferred's already done, it'll immediately resolve, but you don't know that it's already done. That's the power here, so you don't have to know what state your app is in. You can say, wait till this deferred is through, wait till the Ajax call is done, and then run some function that needs the guaranteed data or something like that. Really powerful stuff. Dot then has a pretty syntax. If you're familiar with the hover syntax, where it takes two functions, one for mouse over and one for mouse out, or enter or leave, I'm not sure which, then does the same thing. It takes two function references, so you can pass in a, the first one will fire when done or success happens, and the second function will happen when fail or reject happens. Nice little bit of sugar there. You can make dependent Ajax calls. This kind of scenario happens all the time. You go to the server to get a user's Twitter name and their Facebook stuff. When that comes back, then you ask Twitter and Facebook for some data. So you have like a complex Gantt chart of things that need to happen in a chain off of each other. You can do that really easily using then, when, and pipe to get all these together and making sure that they don't execute before they have any dependent data. You can memoize expensive operations. So you can use deferreds to store parameters that are passed to callbacks. Cool stuff. Not that many things that are done client-side are expensive, but if you're generating Fibonacci numbers or something like that, you can cash that data in a pretty effective way. You can implement a publisher subscriber pattern using notify and progress. I don't know if you're familiar with that pattern. It basically, think of a messaging app where you don't care where the message comes from and the person sending the message doesn't care where it goes, but it's like posting to a bulletin board. If you have an app that warrants that kind of architecture, deferreds can really help you make that more efficient and you won't have to write very much code to get it done. So some best practices for using deferreds. When in doubt, return a deferred. You might need it. Better yet, just return a promise. So the promise, again, is that subset of a deferred object. All it lets you do is hang additional callbacks on that deferred. What it doesn't let you do explicitly is change the state of that deferred. So that protects your code, so it's a lot more predictable. And again, this is more useful if you're gonna make it a reusable library or publish it so that third-party users can get access to your deferreds. They're very powerful as properties stored on objects. So in our example where we had pages that had deferreds saved on them, from any point in the app, you can check to see if that page has its data so you can wait until you have to render it or there are a number of scenarios where that becomes really useful. So this.dfd is all over my code. You can make your code prettier. They make any kind of time-based language much more expressive. So when you're wrapping up an API, you can make it so that anyone can understand your code. They'll get something and then do this. And then when both of those are done, proceed there. And if it fails, fire that. It's just the way you would talk and you can actually do that in your code. That's good stuff. Make your life easier. Deferds are really great. You can write a lot less code by relying on what's already under the hood in jQuery. So just the six points really quickly. I'll go over those again. You can bundle Ajax calls together and know when they're all done. You can normalize interacting with different objects, specifically on our single page app. We had pages that did or did not have data but deferreds, functions that use deferreds like when don't care if it's really a deferred or not. You can implement a really efficient caching system in about 10 lines of code, which is pretty cool. You can make prettier syntax for your code. You can write domain-specific languages if you have a complex API. You can get progress notifications on longer-running operations. This will become more popular and common, I think, as more browsers adopt the HTML5 file upload, which fires progress events. There are a couple of cool libraries that do it too. I don't know his full name. Desandro on GitHub posted a image loading updater for your page so you can tell when all the images are loaded on the page. You can't attach a load handler that gets fired on a cached image and this actually checks to see if it came from the cache as well. And you can get progress along the way of how far along all your images are in coming in the page. And you can also manage animations. So if you ever do any kind of pretty brochure-type sites or if you have a very complex UI for maybe a single-page app with trays and accordions and things like that, you can make sure that it looks pretty and not choppy, not a hack job professional, by using deferreds. So that's the talk. I work at Quick Left. There's my Twitter handle. McPhersonindustries.com is me. There's some credits on the bottom if you want some additional reading. I tried to make them bitly links, but it's a little hard to tell if they're ones or eyes or anything like that. And thanks to Sam and Nico from Quick Left. If you guys have any questions, I will happily answer them.