I imagine that a solution is going to involve some form of promises although I'm struggling to get my head around how I would implement promises in this scenario.
Essentially I have a service which returns $resource, I then use .query() in the controller to get the array of site contexts. The query callback function then passes the response to a $scope function ($scope.getTaskLists).
The getTaskLists function loops through the site contexts using angular.forEach(). For every loop iteration it will use $http to return any task lists within each site context. Using the .success() promise, each $http request calls another for each loop, this time looping through the $http response (task lists). For each task list, another $http request is called which gets the root folder as we need a parameter later on. The .success() promise for this $http call extracts the parameter and then calls $scope.getTaskItems, passing in various parameters including site context and list id.
The getTaskItems function then uses the above parameters to make an $http request to the list, which will return all the list items. The .success() callback here then loops through all the items and pushes the objects to the task scope.
Ultimately the structure resembles something along these lines:
- $resource.query() // get site contexts
- angular.forEach(sites)
- $http().success(... // get task lists
- angular.forEach(taskLists)
- $http().success(... // get root context
- $http().success(... // get task items
- angular.forEach(taskItems)
- $scope.tasks.push(taskItem) // push task item to $scope
What I need to do is run some code once all task items have been pushed to $scope.tasks. Is this possible using promises and is there a better way of streamlining the above code so that it isn't mangled spaghetti code consisting of ajax requests and loops?
Thanks