When working with Angular code, I have a series of chained promises that look like this:
// Defined function in the LoaderService module.
var ensureTypesLoaded = function(){
return loadContainerTypes($scope).then(loadSampleTypes($scope)).then(loadProjectList($scope)).then(loadSubjectTypes($scope));
}
Each of these functions returns a promise that loads data from a resource and also modifies the `$scope` on success or error, for example:
var loadProjectList = function ($scope) {
// Calls getAll method within ProjectService and returns a promise.
return ProjectService.getAll().then(
function (items) {
// Successful load
console.log("Promise 1 resolved");
$scope.projectList = items;
}, function () {
// Error occurred
CommonService.setStatus($scope, 'Error!');
});
};
I plan to use it in controller initialization code as follows:
// In the controller's initialization code
LoaderService.ensureTypesLoaded($scope).then(function () {
// Perform action when all promises are successful
console.log("I will do something here after all promises resolve");
}, function () {
// Handle errors
});
However, the timing is not as expected. The message "I will do something here after all promises resolve" appears before the messages indicating resolved promises within the functions listed in `ensureTypesLoaded`.
I am looking to create a function `ensureTypesLoaded` that:
- Returns a promise that resolves only when all internal promises are resolved
- If any of the internal promises fail, the function should stop and return a rejected promise
- And most importantly, any actions specified in `then()` after calling `ensureTypesLoaded()` should be executed only after everything inside `ensureTypesLoaded` has been resolved
I need help in correctly structuring the chained promises. Thank you!