如何以承诺中止Ajax

时间:2018-07-26 14:04:17

标签: javascript jquery ajax abort

我正在使用类似下面的函数的功能来发送多个ajax请求,以中断长时间运行的进程。我想添加一个取消按钮来中止所有ajax。我试过将所有请求合并到这样的数组中,然后遍历并中止它们……

我已经尝试了许多变体来中止所有ajax请求。

$.xhrPool = [];

$.xhrPool.abortAll = function() {
    $.each(this, function(jqXHR) { 
        jqXHR.abort(); 
    });
};

$.ajaxSetup({
    beforeSend: function(jqXHR) {
        $.xhrPool.push(jqXHR);
    },
    complete: function(jqXHR) {
        var index = $.xhrPool.indexOf(jqXHR);
        if (index > -1) {
            $.xhrPool.splice(index, 1);
        }
    }
});

//gives me... Uncaught TypeError: $.xhrPool.abortAll is not a function

但是它不起作用。有解决方案吗?

这类似于带有Promise的Ajax请求链。

function processBigArray(bigArray, chunkSize) {
    // pre-split array into chunks
    var chunkArray = [];
    for (var i = 0; i < bigArray.length; i += chunkSize) {
        chunkArray.push(bigArray.slice(bigArray, i, chunkSize));
    }

    var results = [];

    // use .reduce() design pattern for chaining and serializing
    // a sequence of async operations
    return chunkArray.reduce(function (p, chunk) {
        return p.then(function () {
            return $.ajax({
                type: 'POST',
                url: ajax.ajax_url,
                data: {
                    'action': 'process_big_array',
                    'array_to_process': chunk
                },
                beforeSend: function () {
                    xxx
                },
                dataType: 'json',
            }).then(function (data) {
                results.push(data);
            });
        });
    }, Promise.resolve()).then(function () {
        // depending upon what your ajax returns, results might be an array of arrays
        // that you would want to flatten
        console.log(results);
        return results;
    });
}

0 个答案:

没有答案