在 AngularJs 中的 $q.all 概念中,当其中一个 promise 给出 404 错误时会发生什么

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

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

我的任务是收集数据并将其存储在数组中,直到URL returns 没有数据。但是,根据 $q.all 实现,我读到如果一个承诺给出 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
    });
  };

$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响应对象的body,如果请求失败则解析为null。它从未被拒绝,因为你已经处理了错误。

因此,如果您将 $q.all() 与一组此类承诺作为参数一起使用,您将得到一个始终被解析为数组的承诺。数组元素将是响应主体,或者对于失败的请求为 null。