Adhering to the traditional REST standards, I have divided my resources into separate endpoints and calls. The primary focus here revolves around two main objects: List
and Item
(with a list containing items as well as additional associated data).
For instance, if a user wishes to retrieve their lists, they could execute a Get request to api/Lists
.
Subsequently, the user might also want to access the items within a specific list by making a Get call to api/ListItems/4
, where '4' is extracted from List.listId
retrieved in the previous request.
All seems to be functioning smoothly so far: utilizing the options.complete
attribute of $.ajax
enables me to reference a callback method, thereby streamlining these processes.
However, matters become considerably more convoluted when aiming to extract elements for all lists at once. For example, implementing a hypothetical library function known as makeGetRequest
which accepts the endpoint and callback function would lead to clearer code. Yet, attempting to fetch 3 elements in a simplistic manner results in:
var success1 = function(elements){
var success2 = function(elements){
makeGetRequest("api/ListItems/3", finalSuccess);
}
makeGetRequest("api/ListItems/2", success2);
}
makeGetRequest("api/ListItems/1", success1);
Unsightly! This would typically warrant reprimand in an introductory programming course followed by guidance towards loops. But how can one employ a loop in this scenario without relying on external storage?
for(var i : values){
makeGetRequest("api/ListItems/" + i, successFunction);
}
function successFunction(items){
//I am invoked multiple times, each time handling only one list's set of items!
}
Even with storage mechanisms in place, it becomes necessary to ascertain when all requests have concluded and acquired their respective data before triggering a master function to compile and process the aggregate information.
Is there a tried and true approach for tackling such situations? Surely, this must have been resolved countless times prior...