Here's an ES6 compatible version of .settle()
which allows all promises to finish and you can then query each result to see if it succeeded or failed:
// ES6 version of settle
Promise.settle = function(promises) {
function PromiseInspection(fulfilled, val) {
return {
isFulfilled: function() {
return fulfilled;
}, isRejected: function() {
return !fulfilled;
}, isPending: function() {
// PromiseInspection objects created here are never pending
return false;
}, value: function() {
if (!fulfilled) {
throw new Error("Can't call .value() on a promise that is not fulfilled");
}
return val;
}, reason: function() {
if (fulfilled) {
throw new Error("Can't call .reason() on a promise that is fulfilled");
}
return val;
}
};
}
return Promise.all(promises.map(function(p) {
// make sure any values or foreign promises are wrapped in a promise
return Promise.resolve(p).then(function(val) {
return new PromiseInspection(true, val);
}, function(err) {
return new PromiseInspection(false, err);
});
}));
}
This can be adapted for the Q library like this:
// Q version of settle
$q.settle = function(promises) {
function PromiseInspection(fulfilled, val) {
return {
isFulfilled: function() {
return fulfilled;
}, isRejected: function() {
return !fulfilled;
}, isPending: function() {
// PromiseInspection objects created here are never pending
return false;
}, value: function() {
if (!fulfilled) {
throw new Error("Can't call .value() on a promise that is not fulfilled");
}
return val;
}, reason: function() {
if (fulfilled) {
throw new Error("Can't call .reason() on a promise that is fulfilled");
}
return val;
}
};
}
return $q.all(promises.map(function(p) {
// make sure any values or foreign promises are wrapped in a promise
return $q(p).then(function(val) {
return new PromiseInspection(true, val);
}, function(err) {
return new PromiseInspection(false, err);
});
}));
}
Usage with your particular code:
var items = ["URL1", "URL2", "URL3"];
$q.settle(items.map(function(url) {
return $http.get(url);
})).then(function(data){
data.forEach(function(item) {
if (item.isFulfilled()) {
console.log("success: ", item.value());
} else {
console.log("fail: ", item.reason());
}
});
});
Note: .settle()
returns a promise that always resolves, never rejects. This is because no matter how many promises you pass it reject, it still resolves, but returns the info on which promises you passed it resolves or rejected.