我在工作中遇到了一个问题:我有一部分安装依赖于服务器。我想这样做:当用户删除服务器时,它会循环安装集合并删除所有相关安装。为此,我使用 jQuery 的“when”函数,据说它会等待服务器的响应,然后转到“then”函数。当只有一个依赖安装时,它可以完美地工作。但是,当有更多安装时会出现问题,因为它会在收到 JSON 响应后立即移动到“then”函数。
问题是:如何让“何时”函数等待所有服务器响应?例如。我通过 $.postJSON 发送了三个删除请求,并希望在收到所有三个响应后继续。如果“何时”不可能,我应该用什么来实现它?如果有帮助,我会使用 KnockoutJS 维护我所有的实体集合。谢谢!
编辑: 我有这样的:
$.when(DeleteDependentInstallations())
.then (function() {
...
});
DeleteDependentInstallations 看起来像(伪代码):
Search the installations collection;
If installation.ID equals server.InstallationID
{
Add to dependent installations collection;
}
Repeat until the whole collection is searched;
for (i = 0; i < dependentInstallations.length; i++)
{
DeleteInstallation(dependentInstallations[i]);
}
DeleteInstallations 是一个使用 $.postJSON 函数的简单函数。
问题是 .then 函数在第一个 JSON 响应后立即执行。
最佳答案
我认为您需要让 DeleteDependentInstallations 返回一组 JQuery deferreds。 $.when允许您将多个参数传递给它,以便让它知道它必须等待每个参数。
我不知道你在做什么的整个背景,但我认为这样的事情可能会奏效:
function DeleteDependentInstallations() {
var installations = getDependantInstallations();
var promises = [];
for (var i = 0; i < installations.length; i++) {
var installation = installations[i];
promises.push(DeleteInstallation(installation));
}
return promises;
}
function DeleteInstallation(installation) {
//do whatever here, but return the result of $.ajaxPost
return $.post('/foo', installation);
}
现在,当您使用该方法时,它应该等待所有返回的 promise 完成。
$.when.apply(null, DeleteDependentInstallations()).then(function() { alert('wee!'); });
.apply() 是为了让我们可以将数组作为参数集合传递。
编辑:我在脑海中混淆了“延期”和 promise 。 Deferreds是 $.ajax 调用返回的内容,以及一个 promise是 $.when() 函数返回的内容。
EDIT2:您可能还想看看 .done()方法,如果 .then() 的行为不符合您的需要。
关于javascript - 如何在具有更多 postJSON 查询功能时使用 jQuery?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12147136/