8

I'm trying to understand $.when, and I can see that it can be useful when you want to wait for multiple deferreds before proceeding. However, I'm not sure I understand what the use-case is for using $.when with one deferred. To illustrate:

var deferred = $.Deferred();

// Is this ever useful?
$.when(deferred).then(...)

// Or can I always do this?
deferred.then(...)
Abdullah Jibaly
  • 53,220
  • 42
  • 124
  • 197

2 Answers2

6

From the $.when [docs] documentation:

If a single Deferred is passed to jQuery.when, its Promise object (a subset of the Deferred methods) is returned by the method.

So $.when(deferred).then(...) is the same as deferred.promise().then(...).

The promise object is just a limited interface to the deferred object. It allows to add callbacks, but not to change the state of the Deferred (resolve, reject it).

So conclusively, there is basically no difference between using $.when and calling .then directly on the deferred object.

I don't think it makes sense to pass a single deferred object explicitly to $.when, since you don't get any advantage. However, there might be situations where you have an unknown number of deferred objects, which means it could also be only one.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

You can always do .then, .then is nothing more than a shortcut for when you need to use both .done and .fail

Kevin B
  • 94,570
  • 16
  • 163
  • 180
  • I think you misunderstood my question. I was asking if wrapping a deferred in $.when adds any additional features to a deferred. Is it ever more useful then calling methods directly on the single original deferred? – Abdullah Jibaly Jun 06 '12 at 15:46
  • `$.when`'s purpose is to create a new deferred object that resolves when all passed in deferreds are resolved, or fail when any one of them fail. If you only pass in one deferred object, the same deferred object is simply returned. You can find all of this information from the api http://api.jquery.com/jQuery.when/ – Kevin B Jun 06 '12 at 15:49
  • I've re-read that page 20+ times, and understand that the promise object is being returned :) My question is when is that useful for 1 deferred? – Abdullah Jibaly Jun 06 '12 at 15:51
  • Regardless of what you pass into $.when, you will get a promise object returned. That is within the first paragraph of the API. If you have a deferred object and you need a promise object instead, call .promise(). using `.when()` is pointless when you can call `.promise()` on the deferred object yourself. – Kevin B Jun 06 '12 at 15:58