On my page I have a form of inputs that take in URLs
<div ng-repeat="parent in parents">
<input ng-model="parent.url" type="text" />
</div>
<button ng-click="addParent()"> Add new link </button>
Later I have a button with ng-click that calls a function in my controller, which checks (asynchronously) if the pages with those URLs exist, along with some other (synchronous) checks.
Somehow I need to wait for results to process, collect them and then display some content depending on those results. I tried looping over all $http calls for each URL:
var results = [];
for (let i = 0; i < parents.length; i++) {
let p = parents[i];
$http.get(p.url).
then((res) => { // pages exists
results.push(true);
}, (err) => { // page doesn't exist
results.push(false);
});
}
But this would return an empty list, since $http calls are asynchronous. Then I can't really check all of my results like this:
if(sync_values){ // this is fine
if(async_values){ // this is never filled in
// do something
}
}
How can I check my results after all $http calls?
UPDATE:
I have tried to implement a factory with $q.all() that would collect promises and resolve them. The tricky bit was to resolve values and not promises; I needed to know which pages existed and which were missing. So I managed to come up with the following code for my factory:
let deferred = $q.defer();
let promises = [];
angular.forEach(parents, function(parent) {
promises.push( $http.get(parent.url).then((res) => {
return true;
}, (err) => {
return false;
}) );
});
$q.all(promises).
then((res) => {
deferred.resolve(res);
});
return deferred.promise;
Now I return a list of booleans (and I know which pages exist and which don't).