I have an array of promises and each promise calls http.get()
.
var items = ["URL1", "URL2", "URL3"];
var promises = [];
//on each URL in items array, I want to create a promise and call http.get
items.forEach(function(el){
return promises.push($http.get(el));
});
var all = $q.all(promises);
all.then(function success(data){
console.log(data);
}).catch(function(reason){
console.log("reason is", reason);
});
what's happening in my case
URL2.get
does not get resolved, and it immediately triggers the catch()
in the $q.all
. As a result of this failure all.then()
never gets invoked.
what I want
I want all the promises to continue even if one of the promise is rejected.
I found a similar post but the solution suggests to use another angular pacakage called Kris Kowal's Q. so I'm wondering how can I achieve it without using external package?
a simple hack might be adding a catch block to promises that return null, and filtering the null results from you promise.all
result, something like:
let items = ["URL1", "URL2", "URL3"]
, promises = items.map(url => $http.get(url).catch(e => null))
, all = $q.all(promises).then(data => data.filter(d => !!d))
all.then(data => {
// do something with data
}).catch(e => {
// some error action
})
same thing in ES5:
var items = ["URL1", "URL2", "URL3"]
, promises = items.map(function(url){
return $http.get(url).catch(function(e){return null})
})
, all = $q.all(promises).then(function(data){
return data.filter(function(d){return !!d}) // filter out empty, null results
})
all.then(function(data){
// do something with data
}).catch(function(e){
// some error action
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With