在AngularJs中的$ q.all概念中,当其中一个promises给出404错误

时间:2016-08-22 19:02:56

标签: angularjs angular-promise angular-services

我正在迭代地调用多个URL,并且对于每个URL请求,我将返回的promise添加到数组中。迭代后,我使用$q.all()来获取结果,并将所有请求中的数据添加到单个数组中。

我的任务是收集数据并将其存储在数组中,直到URL没有返回数据。但是,根据$q.all实现,我读到如果一个promise给出了404错误,那么整批请求将被拒绝。 如何克服这个或任何其他方式来实现我的任务?



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
				});
		};




1 个答案:

答案 0 :(得分:2)

$http.get(resourceUrl)

以上是一个promise,如果请求成功则解析为HTTP响应对象,如果请求失败则拒绝HTTP响应对象。

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

以上是一个承诺,如果请求成功,则解析为HTTP响应对象的主体,如果请求失败,仍然拒绝HTTP响应对象,因为您还没有处理错误情况

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

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

以上是一个promise,如果请求成功,则解析为HTTP响应对象的主体,如果请求失败,则解析为null。它永远不会被拒绝,因为您已经处理了错误。

所以,如果你使用$q.all()这样的promises数组作为参数,你将会有一个永远被解析的promise到一个数组。数组元素将是响应主体,对于失败的请求,则为null。