Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between .catch and .fail in jQuery?

Tags:

The short doc for .fail says:

Add handlers to be called when the Deferred object is rejected.

and the short doc for .catch is exactly the same:

Add handlers to be called when the Deferred object is rejected.

Source: http://api.jquery.com/category/deferred-object/

The arguments accepted by the two methods seem to be different, and the doc of .catch states that .catch is an alias of .then(null, fn)

Are there cases where I should use .fail and others where I should use .catch?

Or ... if I only have one function ... are following commands interchangeable and they only exist for compatibility/historical reasons?

a) .fail(fn)  b) .catch(fn)  c) .then(null, fn) 

I created a jsFiddle:

https://jsfiddle.net/sq3mh9j5/

If there is a difference, could you please provide some examples since I am new to jquery and not yet familiar with all promise terms.

Why does the doc of .catch does not reference the doc of .fail and clarify the difference/similarity?

Edit I found some notes in the 3.0 release notes that the behavior of .then changed. https://blog.jquery.com/2015/07/13/jquery-3-0-and-jquery-compat-3-0-alpha-versions-released/ Nevertheless I am still unsure when to use .fail and when to use .catch.

like image 846
Stefan Avatar asked Apr 13 '17 09:04

Stefan


People also ask

What is deferred in JQuery?

Deferred() method in JQuery is a function which returns the utility object with methods which can register multiple callbacks to queues. It calls the callback queues, and relay the success or failure state of any synchronous or asynchronous function.

What is JQuery promise function?

promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended. By default, type is "fx" , which means the returned Promise is resolved when all animations of the selected elements have completed.


1 Answers

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");   }) 

Note that catch(fn) is an alias of then(null, fn).

like image 106
Jack Wilsdon Avatar answered Oct 01 '22 16:10

Jack Wilsdon