How to override jQuery promise callback

2019-07-19 04:50发布

问题:

I've created a convenience 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 great, because now I don't have to specify the error handler function in 50 different places.

But sometimes I need to override the default error handler with a custom one. When I do this, however, 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?

回答1:

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

You cannot.

or override it?

You could undo what it did (overriding its effects). However, you should better avoid adding the general handler at all - to do that, you will have to change your convenience method. I'd recommend a custom handler as an optional parameter:

function myAjaxFunction(url, data, customHandler) {
    return $.ajax({
        url: url,
        data: data

    }).fail(customHandler || myErrorHandler);
}