在jQuery AJAX调用中有没有类似于'finally'的模拟?

Oli*_*ins 65 javascript ajax jquery promise

在jQuery AJAX调用中是否存在Java'finally'模拟?我这里有这个代码.在我总是抛出异常,但我总是希望它转到then()方法.

    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");
    });
Run Code Online (Sandbox Code Playgroud)

我曾尝试使用done(),complete()和另一个always(),但似乎没有任何效果.

这是JSFiddle:

http://jsfiddle.net/qv3t3L0m/

Raf*_*sco 92

看这个例子:

$.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). 
        }
    });
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请访问:http://api.jquery.com/jquery.ajax/

  • `.complete()`已被弃用; 现在使用`.always()`.http://api.jquery.com/jQuery.ajax/ (23认同)
  • @mlg:complete参数不被弃用,它们仅不建议使用.complete()回调,因为现在jqXHR对象实现了Promise接口。查看此问题的答案:/sf/ask/1107479901/ (4认同)
  • 喜欢FUNFAR动词:D (2认同)

jru*_*ell 38

.always()应该管用.请参阅http://api.jquery.com/jQuery.ajax/上"jqXHR对象"部分.

jqXHR.always(function(data | jqXHR,textStatus,jqXHR | errorThrown){}); 完整回调选项的替代构造,.always()方法替换了不推荐使用的.complete()方法.

响应成功的请求,函数的参数与.done():data,textStatus和jqXHR对象的参数相同.对于失败的请求,参数与.fail()的参数相同:jqXHR对象,textStatus和errorThrown.有关实现细节,请参阅deferred.always().

另见http://api.jquery.com/deferred.always/


Dav*_*lin 9

以下建议在jQuery中不起作用,因为jQuery的promise实现不处理传递给当时的方法中抛出的错误.我只是把它们留在这里作为jQuery是承诺/ A +兼容可能的例证.正如Bergi正确指出的那样,您必须手动将代码包装在自己的try catch块中.

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");
});
Run Code Online (Sandbox Code Playgroud)

虽然我不确定jquery的promise是否始终支持,但另一种方法是使用then(再次)并传递与successHandler和errorHandler相同的函数,如下所示:

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");
});
Run Code Online (Sandbox Code Playgroud)