等待几个 ajax 调用完成,然后执行某些操作



我有这个:

$("#grid tbody tr").each(function () {
    saveRow(model));
});
getAllRows();
...

saveRow的方法如下所示:

$.ajax(
{
    type: 'POST',
    contentType: 'application/json',
    url: "myUrl",
    data: JSON.stringify(model),
    success: function (data) {
        whatever();
    }
});

发生的情况是,我想调用已更改的每个网格行的saveRow并保存它,当它们全部保存时,调用getAllRows函数。

目前发生的事情是,当我调用getAllRows时,并非所有saveRow都已完成,导致返回的数据一半改变,一半不变。

如何确保仅在网格中每一行的saveRow完成后调用getAllRows

编辑

以下是有关当前实现的更多详细信息:

// ajax function to save individual row
function saveRow() {
    $.ajax(
    {
        type: 'POST',
        contentType: 'application/json',
        url: "myUrl",
        success: function (data) {
            whatever();
        }
    });
}
// array to store ajax functions called
var requests = [];
// function that iterates through all rows and saves them
$("#grid tbody tr").each(function () {
    // adding the ajax function call to the array
    requests.push(saveRow());
});

...
// supposedly, call getAllRows when all the saveRow ajax calls are done
$.when.apply($, requests).then(function () {
    getAllRows();
});

这是不起作用的,在所有其他getAllRows完成之前调用

ajax函数将为您提供一个 promise 对象。 如果将这些承诺传递给 JQuery $.when 函数,它将返回另一个承诺,当您传递的每个承诺都将解析时,该承诺将解析:

var promise1 = $.ajax({ /* your saveRow ajax */});
var promise2 = $.ajax({ /* your saveRow ajax */});
$.when(promise1, promise2).done(function(promise1, promise2) {
    getAllRows();
});

如果要等待多个 safeRow ajax,还可以使用 apply 函数向 when 函数提供一系列承诺:

var promises = [];
promises.push($.ajax({ /* your saveRow ajax */}));
promises.push($.ajax({ /* your saveRow ajax */}));
//...
$.when.apply($, promises).done(function() {
    getAllRows();
});

你可以做一些事情,

比如
var d1 = $.ajax({...});
var d2 = $.ajax({...});
$.when(d1, d2 );
.then(function() {
    ...
})

如果异步函数不起作用 - 您可以尝试使用变量作为条件,即

如果要调用 10 个 saveRows,则让全局变量 saveRowsRun = 0。在每个 SaveRow 函数集的末尾 saveRownsRun++让函数 getAllRows() 在每个 saveRows 函数的末尾运行,但在 if 语句中;

if(saveRownsRun == 10){
    getAllRows();
}

这将确保 if 尝试在每行后触发,但只能在最后一行之后触发。

最新更新