9
 $.ajax("example.php").done(function ()
 {
     alert(...);
 }).fail(function ()
 {
     alert(...);
 }).always(function ()
 {
      alert(...);
 });

vs

  $.ajax("example.php",

      success: function ()
      {
          alert('');
      },
      error: function ()
      {
          alert('');
      },
      complete: function ()
      {
          alert('');
      }
  );

Sorry , I can't see any advantages

Can you please explain ?

Or maybe can you give me example of the former which cant be accomplished by the latter...?

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • 2
    Shrug... I guess the former may feel more jQuery-y to some. I don't think there's more than a stylistic advantage here. – Pekka Nov 06 '11 at 20:46

3 Answers3

5

For starters, the second code block isn't even syntactically valid. I'd call that an advantage of the first :P


But in all seriousness:

It's just a different syntax for achieving the same end result. One immediate advantage is that you can wire up multiple functions for each outcome with deferred:

$.get("example.php").done(function ()
{
    alert("success 1");
}).done(function ()
{
    alert("success 2");
});

otherwise you'd have to do it like so:

function done1()
{
    alert('success 1');
}
function done2()
{
    alert('success 2');
}

$.ajax('example.php',
{
    success: function ()
    {
        done1.apply(this, arguments);
        done2.apply(this, arguments);
    }
});

Other advantages, quoted from How can jQuery deferred be used?

  • Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.
  • ...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.
  • A deferred can be used in place of a mutex. This is essentially the same as the multiple ajax usage scenarios.
Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Still hard to see any difference. since when im running "example.php" im waiting for an answer ( success or done nevermind) .I'm looking for some hard evidance of advantages ...:) – Royi Namir Nov 06 '11 at 20:55
  • 1
    See my edit for fancier cases. Don't like the deferred API? Don't use it. – Matt Ball Nov 06 '11 at 20:59
  • 1
    I just saw the example from http://stackoverflow.com/questions/4869609/how-can-jquery-deferred-be-used and this line `return cache[ val ] || $.ajax('/foo/',...` made me realize that i can use `when` in callbackFunction **REGARDLESS** the response which can be from the cache or from the ajax call...nice. thank you. – Royi Namir Nov 06 '11 at 21:02
4

I'd say deferred objects are just another step in the evolution of jQuery.

Before them, it was only possible to pass the callbacks to $.ajax in the configuration object. Having deferrds, you can now handle all asynchronous or even synchronous execution with them, which leads to a more unified interface. This is the advantage: simplification through unification.

Something similar happened with the introduction of on. There is no real advantage of on over bind, but it simplifies event handling in the sense that it combines the functionality of bind, live and delegate. The result is a unified API for event handling. Either I use two times the same function, on, or bind and delegate.

In a similar way, if I want to make two dependent Ajax calls, I can either use two $.ajax calls plus $.when, which is what I'm familiar with and is not any different than making one or multiple calls, or I nest one call inside the other, which requires me to think differently about how the execution takes place.

Deferred objects are a unified, general way for asynchronous code execution. That does not mean that the previous way of adding callbacks should be removed, it would break a lot of code. And besides that, it is still closer to the methods of the original XMLHTTPRequest object, which some people might just prefer.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Does deferred objects is only for Async calls ? – Royi Namir Nov 06 '11 at 21:15
  • I still havent figure when i have to use `when` I saw examples which lets you do `then` without `when`...can you explain? – Royi Namir Nov 06 '11 at 21:19
  • No, that's why I changed it to "asynchronous or even synchronous execution"... I was just often using it in an asynchronous way and I think that's their main purpose. – Felix Kling Nov 06 '11 at 21:19
  • `then` is a method of every deferred object, so you can use it whenever you have such an object. `when` just returns another deferred or promise object. – Felix Kling Nov 06 '11 at 21:20
1

Main benefit with deferred objects is that you can pass them around, so for complex cases where ajax execute code doesn't know who else is interested in callback or you don't want to hardcode it, it can just pass around the deferred object to interested plugins/module code.

e.g.

var defer = $.get("example.php");
for(var i=0; i<ajax_observers.length;i++){
    ajax_observers[i].hook(defer)
}

Same thing can be done via callbacks, but then you will have to write an interface to get callback functions from observers, and that is not flexible, with deferred observers can do anything with deferred objects.

Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219