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

后端 未结 6 515
北荒
北荒 2021-02-04 22:45

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

6条回答
  •  孤独总比滥情好
    2021-02-04 23:26

    The below suggestions will not work in jQuery, because jQuery's promise implementation does not handle errors thrown in methods passed to then. I am only leaving them here as an illustration of what could be possible if jQuery was promises/A+ compliant. As Bergi rightly points out, you will have to manually wrap your code in your own try catch block.

    call.xmlHttpReq = $.ajax({
        url : url,
        dataType : 'json',
        type : 'GET'
    }).then(function(processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
    
       throw "something";
    
    }).always(function() {
    
        alert("i want to always run no matter what");
    });
    

    Although I'm not sure if jquery's promise supports always, an alternative would be to use then (again) and pass the same function as both successHandler and errorHandler, like this :

    call.xmlHttpReq = $.ajax({
        url : url,
        dataType : 'json',
        type : 'GET'
    }).then(function(processedDataOrXHRWrapper, textStatus, xhrWrapperOrErrorThrown) {
    
       throw "something";
    
    }).then(function() {
    
        alert("i want to always run no matter what");
    },
    function() {
    
        alert("i want to always run no matter what");
    });
    

提交回复
热议问题