检测AJAX呼叫循环何时完成

Jon*_*ood 2 javascript ajax jquery

我有一个网页,可以将无限数量的项目提交回服务器进行处理.

我决定使用AJAX调用将这些项目以25个为一组提交给Web服务.所以我的循环看起来像这样:

// Submit elements
for (var i = 0; i < ids.length; i += 25) {

    var productIds = ids.slice(i, Math.min(i + 25, ids.length - 1));

    $.post('/Services/ImportProducts.asmx/ImportProducts', JSON.stringify({ importProductIds: productIds }))
    .done(function (result, statusText, jqxhr) {

        // TODO: Update progress

    })
    .always(function () {
        // TODO: Test for error handling here
    });
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,这似乎是对的.但是,当所有处理完成后,我想刷新页面.鉴于上面的代码,我没有看到在最后一次AJAX调用完成时执行任务的简单方法.

由于$.post()是异步的,因此该循环将在AJAX调用之前完成.由于AJAX调用可以以与提交时不同的顺序完成,因此我不能简单地测试我上次提交的调用何时完成.

我怎么知道这段代码什么时候完成?

kly*_*lyd 6

你可以利用jQuery的承诺来做到这一点.一般工作流程涉及将每个promise添加到数组中,然后使用jQuery应用该数组,以便在返回所有promise 执行另一个回调.

这样的事情应该有效:

var promises = []
for (var i = 0; i < ids.length; i += 25) {

    var productIds = ids.slice(i, Math.min(i + 25, ids.length - 1));

    var promise = $.post('/Services/ImportProducts.asmx/ImportProducts', JSON.stringify({ importProductIds: productIds }))
    .done(function (result, statusText, jqxhr) {

        // TODO: Update progress

    })
    .always(function () {
        // TODO: Test for error handling here
    });

    promises.push(promise);
}

/*
    Note, the "apply" function allows one to unwrap an array to parameters for a
    function call. If you look at the jQuery.when signature, it expects to be 
    called like: $.when(promise1, promise2, promise3). Using .apply allows you 
    to satisfy the signature while using an array of objects instead.

    See MDN for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
*/
$.when.apply($, promises)
    .done(function() {
        console.log("All done!") // do other stuff
    }).fail(function() {
        // something went wrong here, handle it
    });
Run Code Online (Sandbox Code Playgroud)