2016-08-22 23 views
0

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

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

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

+1

错误处理程序在您的个人要求?你可以发布你现有的代码吗? – tymeJV

+0

@tymeJV:请找到代码。 – Dravidian

回答

2
$http.get(resourceUrl) 

以上是被解析为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; 
}) 

上面是如果请求成功,其解析为HTTP响应对象的主体上的承诺,并且其被解析为空如果请求失败。它从来没有被拒绝,因为你已经处理了错误。

因此,如果您使用$q.all()以及作为参数的这样的承诺数组,您将有一个将始终解析为数组的承诺。数组元素将是响应主体,对于失败的请求则为null。

+0

您还可以解释一下,我怎么才能从** foreach **循环(depthRange)中出来_首次响应为null_(当第一次收到URL请求的404错误时)。 – Dravidian

+0

请勿使用forEach。使用一个好的旧循环。我正在谈论第二个循环。在这种情况下,你不能摆脱第一个问题,因为这一点,你还没有任何回应。 –

+0

因此,在我的第一个forEach,根据你,如果我的数组是从0到1000的整数集,它会调用GET方法1000次?我不能在任何时候没有得到数据就终止循环? – Dravidian

相关问题