Angular $q returning promise multiple $http calls

后端 未结 3 2101
梦毁少年i
梦毁少年i 2021-01-05 07:16

I\'m working on an $http call that loops over each of multiple api\'s and returns all of the data in one object. I usually have the promise ready to resolve when the $http c

3条回答
  •  攒了一身酷
    2021-01-05 08:08

    If you have an arbitrary set of api calls I would do something like this:

    function getSearchData(){
        var deferred = $q.defer();
        var noOfCalls = apiList.length;
        var results = [];
        var called = 0;
    
        angular.forEach(apiList, function(item, key) {
            $http.get(url).then(function(result){
               results.push(result);
               called++;
               if(called == noOfCalls){
                  deferred.resolve(results);
               }     
            })
       });
    
        return deferred.promise;
    }
    

    However if you know what each api call represents its better to use $.all in this way

    function search1(){
          return $http.get(search1Url).then(function(result){
              // do something to it
              return result; 
          });
    }
    
    function search2(){
          return $http.get(search2Url).then(function(result){
              // do something to it
              return result; 
          });
    }
    
    function search3(){
          return $http.get(search3Url).then(function(result){
              // do something to it
              return result; 
          });
    }
    
    function search4(){
          return $http.get(search4Url).then(function(result){
              // do something to it
              return result; 
          });
    }
    
    function getSearchResult(){
    
        return $q.all([search1(), search2(), search3(), search4()]).then(function(results){
           // OPTIONAL  aggregate results before resolving
           return results;
        });
    }
    

提交回复
热议问题