批量发送大量数据

Sending a lot of data in batches

我使用 jQuery CSV 导入器导入 CSV 文件。处理完导入后,我有一个对象,其中包含每一行的对象,如下所示:

{
    {
        'name':'foo',
        'surname':'bar',
        'tel':'0123456789'
    },
    {
        ...
    }
}

因为csv文件可能有10行或者1000行,我现在想把这个数据批量发送到服务器。我已经有一个功能,可以将对象拆分成几块然后发布。

/**
 * @method sendChunks Sends data in chunks to the micro-service
 * @param object {object} Data that needs to be sliced up and sent
 * @param size {int} Size of chunks
 * @param endpoint {string} Where the data needs to be sent
 * @param callback {function} Callback function when all pieces are sent.
 */
function sendChunks(object,size,endpoint,callback) {
    var counter = 0,
        total = 0,
        sendObj = {
            'source':config.source,
            'country_code':config.country_code,
            'language_code':config.language_code,
            'batch_data': [],
        };
    objectLength = object.count();
    $.each(object, function (i, obj) {
        total++;
        if(counter < size && total != objectLength) {
            counter++;
            sendObj.batch_data.push(obj);
        } else {
            $.ajax({
                url: 'some_url',
                type: 'post',
                data: sendObj,
                success: function(data) {
                    if(total == objectLength) {
                        setNotification('Import completed','Contact was successfully imported.','panel-success panel');
                    }
                }
            });
            if(total == objectLength) {
                if(typeof callback == 'function') {
                    callback();
                } else {
                    console.log('failed to call function');
                }
            }
            counter = 1;
            sendObj.batch_data = []
        }
    })
},

问题是,ajax 请求同时触发。我要他们一个接一个开火。如何让它在上一批完成后才发送下一批?

async: false 参数添加到您的 ajax 调用中:

         $.ajax({
            url: 'some_url',
            type: 'post',
            async: false, // <== one by one
            ...

async (default: true)

Type: Boolean

By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().