Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

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

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,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...