Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular -- accessing data of multiple http calls - how to resolve the promises

Tags:

http

angularjs

I am getting stuck on something I think should be straight forward. I need to take data from three different ajax calls, combine and process all three, and display the resulting array to the user.

In its simplest form my code looks like this:

function giftControler ($scope, $http) {
  var names = $http.get("names.json"),
      naughty = $http.get("naughty.json"),
      nice = $http.get("nice.json");

I understand that my variables are assigned to promises, not actual results, and that the http request have been passed to the event queue. If I follow these with executable statements these variables will be undefined. I don't understand how to wait for these promises to resolve in order to continue processing them.

What I would like to do is immediately add the code:

      for (var i=0; i<names.length; i++){
        for (var j=0; j<nice.length; j++){
          if (names[i] === nice[j]){
            names[i] = names[i] + "--Yay!!";
          };
        };
      };                
      $scope.kids = names;

The problem is that I can't just work off of the promises as if they were resolved arrays. Javascript will see these for statements right after the http calls and try to execute them immediately, even though the promises have not been resolved.

Where I get stuck is that the $http api is giving me a promise object with three functions: error, success & then. I am not sure what to do with that in this case. I need a single success function for all three. I need all three to resolve, then process the data in each, and then assign the result to an angular model.

I am sure I am missing something obvious, but does anyone have a suggestion? In my real work I have several ajax calls multiple data sources and a lot of processing (comparing values, sorting, concatenating, etc) to come up with one good data collection, but I can't get passed this issue.

Thanks,

like image 838
MyTimeFinder Avatar asked Jan 27 '13 08:01

MyTimeFinder


1 Answers

You can use $q's function 'all':

function giftControler ($scope, $http, $q) {
  var names = $http.get("names.json"),
      naughty = $http.get("naughty.json"),
      nice = $http.get("nice.json");
  $q.all([names, naughty,nice]).then(function(arrayOfResults) { 
      ... This callback would be called when all promised would be resolved
    });

This way is little bit cleaner.

Here is link to docementation: http://docs.angularjs.org/api/ng.$q

like image 61
Valentyn Shybanov Avatar answered Oct 31 '22 14:10

Valentyn Shybanov