Is there any analog to a 'finally' in jQuery AJAX calls?

Oliver Watkins picture Oliver Watkins · Apr 10, 2013 · Viewed 57.6k times · Source

Is there a Java 'finally' analogue in jQuery AJAX calls? I have this code here. In my always I throw an exception, however I ALWAYS want it to go to the then() method.

    call.xmlHttpReq = $.ajax({
        url : url,
        dataType : 'json',
        type : 'GET'
    }).always(function(processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {

       throw "something";

    }).then(function() {

        alert("i want to always run no matter what");
    });

I have tried to use done(), complete(), and the another always(), but nothing seems to work.

Here is JSFiddle :

http://jsfiddle.net/qv3t3L0m/

Answer

Rafael Gomes Francisco picture Rafael Gomes Francisco · Feb 12, 2014

See this example:

$.ajax({
        type: "GET",
        dataType: dataType,
        contentType: contentType,
        async: TRUE,
        url: $('html form:nth-child(1)').attr('action') + "?" $('html form:nth-child(1)').serialize(),
        success: function(data) {
            console.log("FUNFOU!");
        },
        error: function(data) {
            console.log("NÃO FUNFOU!");
        },
        complete: function(data) {
            console.log("SEMPRE FUNFA!"); 
            //A function to be called when the request finishes 
            // (after success and error callbacks are executed). 
        }
    });

For more informations: http://api.jquery.com/jquery.ajax/