Conceptually they are not the same thing, but the result produced is exactly the same. The success
and error
functions are called callbacks . In turn, the functions done
and fail
are methods of a Promise .
Difference between promise and callback
The result is exactly the same because jQuery uses the done
and fail
methods to execute the success
and error
functions. See the code snippet taken from the official repository (line 662):
// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );
In this case, s.success
refers to success
passed in options
, as s.error
refers to error
.
Which one to use?
If you only have a success
and error
function, it makes no difference. Use whichever one you prefer. Using done
and fail
are useful when you need to perform multiple functions on each event:
$.ajax("dominio.com")
.done(fazAlgo1)
.done(fazAlgo2)
.fail(deuErrado1)
.fail(deuErrado2);
Using success
and error
you can not assign multiple callbacks . There is also the callback complete
that is always executed, after running success
or error
. In this case, the similar method in Promise would be always
.
For more information, please refer to the official documentation quoted in the other response
Note: It is important to note that the .success
and .error
methods that the documentation cites as obsolete are not the callbacks success
and error
. These are actually methods in Promise in older versions of jQuery. The callbacks functions can still be used .
Example using callbacks :
Using the callback function success
.
$(() => {
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
method: "get",
dataType: "json",
success: users => {
$(users).each(i => {
console.log(users[i].name);
});
},
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ExampleusingPromise
Usingthedone
methodofthePromiseobjectreturnedby$.ajax
.
$(() => {
const request = $.ajax({
url: "https://jsonplaceholder.typicode.com/users",
method: "get",
dataType: "json"
});
request.done(users => {
$(users).each(i => {
console.log(users[i].name);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>