2016-08-22 24 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

相關問題