What is the difference between .catch and .fail in jQuery?
catch
and fail
are slightly different, in that catch
will return a new (resolved) promise, whereas fail
will return the original promise.
// This will only output "fail"$.Deferred() .reject(new Error("something went wrong")) .fail(function() { console.log("fail"); }) .then(function() { console.log("then after fail"); })
// This will output "catch" and "then after catch"$.Deferred() .reject(new Error("something went wrong")) .catch(function() { console.log("catch"); }) .then(function() { console.log("then after catch"); })
So I think the major difference is what you get out of each.
A catch allows you to run a single function.
A fail allows you to run a number of functions.
Other than that I concur with your findings. They are very similar.
I added an example code to showcase how fail will run both functions, and the catch will only run the one.
$.ajax({ url: "abc" }).done(function (data) { }).fail(function () { alert("a"); }, function () { alert("b"); }) .catch(function () { alert("c"); }, function () { alert("d"); });
If you run this you get 'a','b','c' and then 'd' doesn't run.
I hope this simple example showcases the difference.