当其中一个失败时,如何处理一组延迟

时间:2014-01-23 01:03:52

标签: javascript ajax jquery jquery-deferred

我有一系列填充页面上的列的ajax调用。

var doneDefers = function(defer) {
        // leftColDefer is another deferred that sets some header info
    $.when(defer, leftColDefer).done(function(req1, req2){
        var data = req1[0],
        head = req2[0];
        // spit this data out to elements on the page   

    });
};  
for(i=0;i<window.ids.length;i++){
    defer[i] =  $.ajax({
        url: 'api/get_runs_stats.php',
        type: 'GET',
        dataType: 'json',
        data: {
            run_id: window.ids[i]
        }
    });
    doneDefers(defer[i]);
}

这很好用。如果一个ajax调用失败,那么没有任何东西可以吐出来,而且一切都是正确的。 现在我想根据吐出的所有数据做一些计算。

$.when.apply(null, defer)
    .done(function() {
        var args = Array.prototype.slice.call(arguments);
        calcDeltas();

    })
    .fail(function() {
        var args = Array.prototype.slice.call(arguments);
        console.log('in list fail');
    });

完成功能正常工作没有任何ajax调用失败。如果其中一个失败,我进入失败功能,我无法访问其他运行的任何返回数据。 arguments数组只有失败的调用数据。

我想对传递的数据集进行计算。当其中一个失败时,如何从好的调用中获取数据?

1 个答案:

答案 0 :(得分:1)

我不确定这是最简单的解决方案,但它有机会工作。

var ajax_always_promises = [],//to be populated with promises that (barring uncaught error) are guaranteed to be resolved.
    data_arr = [],//an array to be (sparsely) populated with asynchronously delivered json data.
    error_arr = [];//an array to be (sparsely) populated with ajax error messages.

$.each(window.ids, function(i, id) {
    var dfrd = $.Deferred();
    var p = $.ajax({
        url: 'api/get_runs_stats.php',
        type: 'GET',
        dataType: 'json',
        data: {
            run_id: window.ids[i]
        }
    }).done(function(json_data) {
        data_arr[i] = json_data;//intentionally not `data_arr.push(json_data);`
    }).fail(function(jqXHR, textStatus, errorThrown) {
        error_arr[i] = textStatus;//intentionally not `error_arr.push(textStatus);`
    }).always(dfrd.resolve);

    ajax_always_promises[i] = dfrd.promise();
    doneDefers(p);
});

$.when.apply(null, ajax_always_promises).done(function() {
    //The data in the (sparsely) populated arrays `data_arr` and `error_arr` is available to be used. 
    var i, id, success_count=0, error_count=0;
    for(i=0; i<Math.max(data_arr.length,error_arr.length); i++) {

        //Here, the index i corresponds to the original index of window.ids ...
        //...that's the advantage of sparsely populating the arrays.
        id = window.ids[i];
        if(data_arr[i]) {
            //Here, do whatever is required with `data_arr[i]`, and `id` if needed.
            success_count++;
        }
        else if(error_arr[i]) {
            //Here, do whatever is required with `error_arr[i]`, and `id` if needed.
            error_count++;
        }
    }
    console.log("Success:errors: " + success_count + ':' + error_count);
});

未经测试 - 可能需要调试