简体   繁体   中英

What's the correct way to iterate through array and sending multiple ajax requests

I currently have some ajax that sends an array to php for processing. The array size at most would be around 1000 elements which will be enough for the server to time out while the php is processing. I would like to chunk the array and send it in batched ajax requests (or maybe just one at a time) that will each finish without timing out.

Below is my basic code structure. I'm trying to use promises and iterate through the chunks:

Here's the basic structure of the working function (non-promise version):

function ajax_function(big_array) {
    $.ajax({
        type: 'POST',
        url: ajax.ajax_url,
        data: {
            'action': 'process_big_array',
            'array_to_process': big_array
        },
        beforeSend: function () {
            xxx
        },
        dataType: 'json',
        success: process_big_array_chunk_handler,
        error: function (xhr, desc, err) {
            console.log(xhr);
            console.log('Details: ' + desc + '\nError: ' + err);
        }
    });
}

Here's work in progress trying to add the loop and promise.

function ajax_function(big_array) {
    var big_array_chunks = make it into chunks somehow;
    $.each(big_array_chunks, function (big_array_chunk) {
        var request = $.ajax({
            type: 'POST',
            url: ajax.ajax_url,
            data: {
                'action': 'process_big_array_chunk',
                'array_to_process': big_array_chunk
            },
            dataType: 'json'
        }).done(function (data) {
            process_big_array_chunk_handler(data);
        }).fail(function (xhr, desc, err) {
            console.log(xhr);
            console.log('Details: ' + desc + '\nError: ' + err);
        });
    });
}

Trying to get my head around how this all fits together:

  • each iteration of loop
  • responses from php
  • how to use my response handler when it's all done

fyi, this is being done within the context of WordPress if that matters.

Response to Bergi:

function ajax_function(big_array) {
    var big_array_chunks = make big_array into chunks somehow;
    var request = $.ajax({
        type: 'POST',
        url: ajax.ajax_url,
        data: {
            'action': 'process_big_array_chunk',
            'array_to_process': big_array_chunk
        },
        dataType: 'json'
    }).then(function (data) {
        process_big_array_chunk_handler(data);
    });
}

The simplest solution I can think of is to just pre-chunk the array and then just use the .reduce() design pattern for serializing promises.

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;
    });
}

// usage
processBigArray(someBigArray, 50).then(function(results) {
    // process results here
}).catch(function(err) {
    // deal with error here
    console.log(err);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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