Dravidian
Dravidian

Reputation: 339

In $q.all concept in AngularJs, what happens when one of the promises gives 404 Error

I am calling multiple URLs iteratively and for each URL request, I am adding the returned promise into an array. After iteration, I am using $q.all()to get the results and add the data from all the requests into a single array.

My task is to collect and store the data in an array until a URL returns no data. But, as per $q.all implementation, I read that if one promise gives 404 error, then the whole batch of requests will be rejected. How to overcome this OR Any other ways to achieve my task?

var calculateMutationsInDepth = function(){
			var depthRange=[0,1,2,3];
			var promises[]; // Promises array
                    //Calling GET request for each URL
			depthRange.foreach(function(depth){
                        var resourceUrl = urlService.buildSonarUrlsWithDept(depth);
			promises.push($http.get(resourceUrl));
		    });
			
  //Resolving the promises array
			$q.all(promises).then(function(results){
				var metricData=[]; //Array for appending the data from all the requests
				results.forEach(function(data){
					metricData.push(data);
				})
				analyzeMutationData(metricData); //calling other function with collected data
				});
		};

Upvotes: 0

Views: 718

Answers (1)

JB Nizet
JB Nizet

Reputation: 691845

$http.get(resourceUrl)

the above is a promise which is resolved to an HTTP response object if the request succeeds, and rejected to an HTTP response object if the request fails.

$http.get(resourceUrl).then(function(response) {
    return response.data;
})

the above is a promise which is resolved to the body of an HTTP response object if the request succeeds, and still rejected to an HTTP response object if the request fails, since you haven't handled the error case

$http.get(resourceUrl).then(function(response) {
    return response.data;
}).catch(function(response) {
    return null;
})

or

$http.get(resourceUrl).then(function(response) {
    return response.data;
}, function(response) {
    return null;
})

the above is a promise which is resolved to the body of an HTTP response object if the request succeeds, and which is resolved to null if the request fails. It's never rejected, since you've handled the error.

So, if you use $q.all() with an array of such promises as argument, you'll have a promise which will always be resolved, to an array. The array elements will be the response bodies, or null for the requests which failed.

Upvotes: 2

Related Questions