Using jquery deferred to synchronize animation and ajax

I am trying to understand the whole deferred concept and I am trying to use it to synchronize the fadeIn / fadeOut along with an Ajax call.

I basically switch the content on the page:

  • Get content using ajax
  • In response to FadeOut
  • Replace content
  • Fadein

However, if I understand deferred correctly, I could do something like this:

  • fadeOut and at the same time initialize the contents of the fetch with ajax
  • When both fadeOut and Fetch are completed: Change contents
  • Fadein

Some code for the original solution:

 $.get(url, function(page) { $('#content').fadeTo(100, 0, 'linear', function() { $(this).html(page.text).fadeTo(400, 1, 'linear'); }); } 

I am trying to do something like this:

 var deferred1 = $.get(url); var deferred2 = $('#content').fadeTo(100, 0, 'linear').promise(); $.when(deferred1, deferred2).done(function() { $('#content').html(page.text).fadeTo(400, 1, 'linear'); }); 

I just can't figure out how to use it. And should I use this or that? Should I use the pipe in a smart way? Do I need a promise ?

What will be the "standardized" way to implement this?

+6
source share
1 answer

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 .

+6
source

All Articles