Monday, October 16, 2017

Checking asynchronous values with a loop of $http calls

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?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/10/16/checking-asynchronous-values-with-a-loop-of-http-calls/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment