How to override jQuery promise callback

I created a convenient method that adds a default error handler for my ajax calls:

function myAjaxFunction(url, data) { return $.ajax({ url: url, data: data }).fail(myErrorHandler); } 

So far, this works fine, because now I do not need to specify the error handler function in 50 different places.

But sometimes I need to override the default error handler with a custom one. However, when I do this, it calls both error handlers:

 myAjaxFunction("myurl", "mydata").fail(myCustomErrorHandler).then(doSomething); 

How do I get it to override or remove the previous error handler from the chain?

+2
source share
1 answer

How can I delete it to remove the previous error handler from the chain?

You can not.

or override it?

You can undo what he did (overriding his effects). However, you'd better avoid adding a generic handler β€” you will have to change your convenience method to do this. I would recommend a custom handler as an optional parameter:

 function myAjaxFunction(url, data, customHandler) { return $.ajax({ url: url, data: data }).fail(customHandler || myErrorHandler); } 
+6
source

Source: https://habr.com/ru/post/954969/


All Articles