When you use $.when (I know, a funny sentence;)), then the values ββpromises are allowed with are passed as arguments to the callback functions. That is, in your done callback, the first argument refers to the allowed value of deferred1 , and the second argument refers to deferred2 (whatever that is).
Now, when the Ajax success callback is called, it gets three arguments:
- answer
- status text
jqXHR object
You are only interested in the first one.
So your setup should be:
var promise1 = $.get(url); var promise2 = $('#content').fadeTo(100, 0, 'linear').promise(); $.when(promise1, promise2).done(function(ajax_success) { $('#content').html(ajax_success[0]).fadeTo(400, 1, 'linear'); });
Also see the $.when documentation .
Do I need a promise ?
No. It seems that $.when calls .promise internally when you pass the jQuery collection. But in other cases you will have to, so it makes sense to do it here, for consistency (thanks Alnitak ).
And should I ...? Do I need ...? What would be??
There are no standard solutions for such problems. promises are incredibly flexible and there are so many ways to use. I think they are not long enough in JavaScript to create standard templates. Find / create something that makes sense for you and be consistent in your application.
The only thing I would recommend doing if you have several promises is placed in an array: jQuery $ .when () with variable arguments .
source share