按照典型的 REST 标准,我将我的资源分解为单独的端点和调用。这里主要讨论的两个对象是 List
和 Item
(当然,列表有一个项目列表,以及与之相关的其他一些数据)。
因此,如果用户想要检索他的列表,他可能会向 api/Lists
发出 Get 请求
然后用户可能想要获取其中一个列表中的项目,并获取 api/ListItems/4
,其中 4 是从 List.listId
检索到的在之前的通话中。
一切都很好:$.ajax
的 options.complete
属性让我指向一个回调方法,因此我可以简化这两个事件。
但是,如果我想获取所有 相关列表的元素,事情就会变得非常困惑。例如,假设我有一个名为 makeGetRequest
的库函数,它接受端点和回调函数,以使此代码更清晰。简单地以天真的方式检索 3 个元素会导致:
var success1 = function(elements){
var success2 = function(elements){
makeGetRequest("api/ListItems/3", finalSuccess);
}
makeGetRequest("api/ListItems/2", success2);
}
makeGetRequest("api/ListItems/1", success1);
恶心!这是编程 101 中的那种事情,我们被打在手腕上并指向循环。但是,如何在不依赖外部存储的情况下通过循环执行此操作?
for(var i : values){
makeGetRequest("api/ListItems/" + i, successFunction);
}
function successFunction(items){
//I am called i-many times, each time only having ONE list's worth of items!
}
即使有了存储,我也必须知道所有何时完成并检索了他们的数据,并调用一些主函数来检索所有收集的数据并对其进行处理。
有处理这个的做法吗?这个问题之前肯定已经解决过很多次了...
最佳答案
尝试使用一堆端点参数:
var params = [];
var results [];
params.push({endpoint: "api/ListItems/1"});
params.push({endpoint: "api/ListItems/2"});
params.push({endpoint: "api/ListItems/3"});
params.push({endpoint: "api/ListItems/4"});
然后您可以在成功处理程序中使其递归:
function getResources(endPoint) {
var options = {} // Ajax Options
options.success = function (data) {
if (params.length > 0) {
results.push({endpoint: endpoint, data: data});
getResources(params.shift().endpoint);
}
else {
theMasterFunction(results)
}
}
$.get(endPoint, options)
}
您可以像这样通过一次调用启动它:
getResources(params.shift().endpoint);
编辑:
为了保持所有内容独立且不在全局范围内,您可以使用函数并提供回调:
function downloadResources(callback) {
var endpoints = [];
var results [];
endpoints.push({endpoint: "api/ListItems/1"});
endpoints.push({endpoint: "api/ListItems/2"});
endpoints.push({endpoint: "api/ListItems/3"});
endpoints.push({endpoint: "api/ListItems/4"});
function getResources(endPoint) {
var options = {} // Ajax Options
options.success = function (data) {
if (endpoints.length > 0) {
results.push({endpoint: endpoint, data: data});
getResources(endpoints.shift().endpoint);
}
else {
callback(results)
}
}
$.get(endPoint, options)
}
getResources(endpoints.shift().endpoint);
}
正在使用中:
downloadResources(function(data) {
// Do stuff with your data set
});
关于javascript - 如何制作干净的异步循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11782914/