jQuery/JS -等待JSON块处理完成后再开始下一个块


jQuery/JS - Wait for JSON chunk to be done processing before starting the next chunk

我想拆分我的700个条目JSON文件,并将它们分成20个块进行处理。

我已经提出了以下代码,当save.php中的操作不需要太长时间时,它可以很好地工作。但是,JSON文件还包含我需要在save.php中下载的图像的url,这使得该过程花费的时间超过300毫秒,并导致触发下一个块。

我当然可以调整时间,但我真正想要的是,一旦save.php中的整个操作完成,脚本就转移到下一个块。有什么办法吗?谢谢!

$.getJSON('data.json', function(products) {
    var time = 300;
    var chunk = 20;
    for (i = 0; i < products.length; i += chunk) {
        (function(index) {
            setTimeout(function() { 
                var out = jQuery.param({'products':products.slice(index, index + chunk)});
                $.post('save.php', out, function(result) {
                  $('.log').append(result);
                });
            }, time);
            time += 300;
        })(i);
    }
});

使用eachLimit可能会满足您的需要。您可以遍历条目,限制并发操作的数量。

async.eachLimit(products, 20,function(elem, cb){
    var out = jQuery.param({'product':elem});
        $.post('save.php', out, function(result) {
        $('.log').append(result);
        cb();
    });
},
function(){
     console.log("success");
})

EDIT使用这种方法,您必须为每个产品做一个帖子,但您可以做20个并行帖子,这不是"好",不知道这对您来说是否有问题?