1

Are there any technical differences between the following callback methods?

1

$.ajax({
  ...
  success: function(data, textStatus, jqXHR) {
    foo(data);
  },
  error: function (jqXHR, textStatus, errorThrown ) {
    bar();
  }
});

2

$.ajax(...)
  .done(function(data) {
    foo(data);
  })
  .fail(function() {
    bar();
  });

3

$.ajax(...)
  .then(function(data) {
    foo(data);
  }, function() {
    bar();
  });

With little experience, I am not sure they are correct examples for passing data to foo(). (Please correct me if I am wrong.)

With done/fail, we can't track other data like jqXHR, textStatus, errorThrown, etc. Am I right?

Is there a complete equivalence for the done/fail method?

From your experience, is one better than/preferred over the others at certain situations?

If I use both success and done/then, will one run before the other definitely or it can't be certain which will run before the other definitely? Or is using success and done/then altogether not recommended?

wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29
user2526586
  • 972
  • 2
  • 12
  • 27
  • 1
    Possible duplicate of [jQuery.ajax handling continue responses: "success:" vs ".done"?](http://stackoverflow.com/questions/8840257/jquery-ajax-handling-continue-responses-success-vs-done) – gyre Mar 17 '17 at 06:21
  • 3
    `.then()` returns a new promise for chaining. `.done()` does not. `.then()` is closer to the promise standard (in JQ 3.0 it is actually standard, not fully in prior versions). `.done()` is entirely a jQuery specific design and is not governed by any promise standard. – jfriend00 Mar 17 '17 at 06:31

1 Answers1

1

One difference between jQuery .done() and .then() is the return value can be changed at .then()

See jQuery deferreds and promises - .then() vs .done()

$.Deferred(function(dfd) {
  dfd.resolve(1)
})
.done(function(n) {
  return n + 1
})
.then(function(res) {
  console.log(res) // 1
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

$.Deferred(function(dfd) {
  dfd.resolve(1)
})
.then(function(n) {
  return n + 1
})
.then(function(res) {
  console.log(res) // 2
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177