简体   繁体   English

jQuery AJAX“总是”不是“总是”被调用

[英]jQuery AJAX `always` isn't “always” called

Specifically, when an error is thrown in the done (or fail ) handler, then always handler is simply not called. 具体来说,当在done (或fail )处理程序中引发错误时, always不会调用always处理程序。

I've "fixed" this like so: 我已经像这样“修复”了这个问题:

xhr.done(delayThrow(function(response) { /* .. do stuff .. */ }));

function delayThrow(fn) {
    return function() {
        try {
            fn.apply(this,arguments);
        } catch(e) {
            setTimeout(function() {
                throw e;
            },10);
        }
    };
}

This works, and (to my surprise) the call stack is left intact*. 这有效,并且(令我惊讶的是)调用堆栈保持不变*。 But it seems like a very hackish solution. 但这似乎是一个非常棘手的解决方案。 Is there a better way, or am I approaching this wrong? 有没有更好的方法,还是我要解决这个错误?

*I assume this is because the exception object is already created and it's just being thrown without factoring in later call stacks like the setTimeout *我认为这是因为已经创建了异常对象,并且该异常对象只是在未考虑诸如setTimeout类的以后调用堆栈的情况下抛出的

So, my guess is that the always callback is (indeed) a bit misleading and only fires when an error occurred during the request, as opposed to after it's already done. 所以,我的猜测是, always回调(确实)有点误导,只有火灾时,在请求期间发生了错误,而不是之后,它已经完成。

Seems like deferred.then() does the job and gets called in every case. 似乎deferred.then()会完成工作并在每种情况下都会被调用。 However, this only seems to fire with jQuery 3+, which is why I can't post a SO sample (limited to version 2 apparently). 但是,这似乎只在jQuery 3+上有效,这就是为什么我不能发布SO示例(显然限于版本2)的原因。

Demo here: https://jsfiddle.net/78ux6jhL/ 演示在这里: https : //jsfiddle.net/78ux6jhL/

Note that deferred.then() takes 3 callback parameters, first one when the initial request was successful, second one when it failed. 请注意, deferred.then() 3个回调参数,第一个参数在初始请求成功时,第二个参数在失败时。 Just pass the same function twice to emulate the actuallyAlways you wanted. 只是通过相同功能的两次模拟actuallyAlways你想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM