For those who havn't used .Deferred before I've annotated the source for it

What are the possible usages of these new methods, how do we go about fitting them into patterns?

I have already read the API and the source, so I know what it does. My question is how can we use these new features in everyday code?

I have a simple example of a buffer class that calls AJAX request in order. (Next one start after previous one finishes).

/* Class: Buffer
* methods: append
*
* Constructor: takes a function which will be the task handler to be called
*
* .append appends a task to the buffer. Buffer will only call a task when the
* previous task has finished
*/
var Buffer = function(handler) {
var tasks = [];
// empty resolved deferred object
var deferred = $.when();
// handle the next object
function handleNextTask() {
// if the current deferred task has resolved and there are more tasks
if (deferred.isResolved() && tasks.length > 0) {
// grab a task
var task = tasks.shift();
// set the deferred to be deferred returned from the handler
deferred = handler(task);
// if its not a deferred object then set it to be an empty deferred object
if (!(deferred && deferred.promise)) {
deferred = $.when();
}
// if we have tasks left then handle the next one when the current one
// is done.
if (tasks.length > 0) {
deferred.done(handleNextTask);
}
}
}
// appends a task.
this.append = function(task) {
// add to the array
tasks.push(task);
// handle the next task
handleNextTask();
};
};

I'm looking for demonstrations and possible uses of .Deferred and .when.

Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when/.then doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then() handler in both cases. jQuery.when() handles a non-Promise/Deferred as a Completed one, immediately executing any .done() or .then() on the chain.

Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.

Two brilliants examples. I implemented something similar to the 2nd one, but with 4 ajax requests, and it performs well, in addition to be far more legible, compact, logic, maintainable, etc. jQuery.Deferred is a real good thing.
– PJPApr 1 '11 at 9:55

I dont understand how the first code example even works: I understand the case where the object is not cached, but if it is then wont cache[ val ] NOT return a promise (the jquery documentation says that the parameter is the data returned by the sender) meaning that the member access of .then will error...right? What am I missing?
– chacham15Dec 7 '14 at 18:53

When using a Deferred as a mutex only, watch out for performance impacts (http://jsperf.com/deferred-vs-mutex/2). Though the convenience, as well as additional benefits supplied by a Deferred is well worth it, and in actual (user driven event based) usage the performance impact should not be noticeable.

Another use that I've been putting to good purpose is fetching data from multiple sources. In the example below, I'm fetching multiple, independent JSON schema objects used in an existing application for validation between a client and a REST server. In this case, I don't want the browser-side application to start loading data before it has all the schemas loaded. $.when.apply().then() is perfect for this. Thank to Raynos for pointers on using then(fn1, fn2) to monitor for error conditions.

You can use a deferred object to make a fluid design that works well in webkit browsers. Webkit browsers will fire resize event for each pixel the window is resized, unlike FF and IE which fire the event only once for each resize. As a result, you have no control over the order in which the functions bound to your window resize event will execute. Something like this solves the problem:

This will serialize the execution of your code so that it executes as you intended it to. Beware of pitfalls when passing object methods as callbacks to a deferred. Once such method is executed as a callback to deferred, the 'this' reference will be overwritten with reference to the deferred object and will no longer refer to the object the method belongs to.

How does this do any serialization? You've already resolved the queue so resizeQueue.done(resizeAlgorithm) is the exact same as resizeAlgorithm. It's a complete sham!
– RaynosMar 1 '11 at 13:24

When the code of your resizeAlgorithm is complex, JavaScript implementation in webkit will loose synchronization when the function is called for each pixel you resize the window. Deferred keeps your callbacks in a queue and executes them in a FIFO order. So, if you add a 'done' callback and it executes immediately because the deferred is already resolved, another 'done' callback that is added to the deferred while the first callback is still executing will be added to the queue and will have to wait for the first callback to return. I hope this answers your question.
– Miloš RašićMar 2 '11 at 12:12

the JS interpreter in the browser is single threaded. Unless your resizeAlgorithm has some async code inside it the entire function should have finished operating before the next call to .done is made.
– RaynosMar 3 '11 at 23:15

@Raynos: I'm aware of that, but I tried to simply call the resizeAlgorithm on resize and it gives a blank white page in webkit browsers while working perfectly in others. The deferred solves this problem. I haven't had enough time to do some deeper research into this. Might be a webkit bug. I don't think the deferred as used in my example would help if resizeAlgorithm had some asynchronous code.
– Miloš RašićMar 4 '11 at 15:58

I've just used Deferred in real code. In project jQuery Terminal I have function exec that call commands defined by user (like he was entering it and pressing enter), I've added Deferreds to the API and call exec with arrays. like this:

the commands can run async code, and exec need to call user code in order. My first api use pair of pause/resume calls and in new API I call those automatic when user return promise. So user code can just use