4

我收到了一个动态异步请求(对于我使用 ajax 的 jsfiddle),无论成功还是失败,我都需要等待,这意味着即使某些请求失败,我只需要知道所有进程都已完成。

//动态:在我的情况下,这是由 ajax 请求产生的,因此后续异步请求的数量是灵活的

所以我最初使用了这段代码:

    $.when.apply($,deferreds).done(function() {
        $("div").append("<p>All done!</p>");
    }).fail(function(){
        $("div").append("<p>Something failed!</p>");
    });

但是在其中一个延迟失败的情况下,将立即调用失败回调。我尝试将其更改为always()但结果是:

Uncaught TypeError: Object # has no method 'always'

那么我怎样才能为此实现一个 always() 类型的解决方案呢?

小提琴

我的原始来源:jQuery Deferred - 等待多个 AJAX 请求完成

4

2 回答 2

9

If you just want to wait a list of $.Deferred to end regardless they are rejected or resolved, you have the solution in my answer in your original source jQuery Deferred - waiting for multiple AJAX requests to finish :

$.when.apply($, $.map(deferreds, function(d) {
    var wrapDeferred = $.Deferred();
    // you can add .done and .fail if you want to keep track of each results individualy
    d.always(function() { wrapDeferred.resolve(); });
    return wrapDeferred.promise();
}));
于 2013-02-14T09:54:36.500 回答
0

好的,就像凯文 B建议的那样。我使用了一个自定义延迟,无论异步请求的结果如何,它都会被解决。

var deferreds = $.map(i, function (count, index){
    var waitingProcess = new $.Deferred(); //Here is the custom deferred
    if(count == 7) {
        $.Deferred().fail(function(){
            $("div").append("<p>Task #" + count + " failed.");
            waitingProcess.resolve(); //resolve it no matter the outcome
        }).reject();
    }else{
        $.post('/echo/html/', {
            html: "<p>Task #" + count + " complete.",
            delay: count
        }).success(function(data) {
            $("div").append(data);
            waitingProcess.resolve(); //resolve it no matter the outcome
        });
    }
    return waitingProcess.promise();
});

小提琴

于 2013-02-13T04:34:50.613 回答