I am geocoding some addresses, sometimes some of them fail. I'd like to be able to get the rest of the results and ignore the failed one so I can display the other coordinates on a map. Currently $q.all will call the errorHandler when one is rejected, so I lose the results of other promises.
$q.all(promises).then(function(coords) {
for (var j = 0;j<coords.length;j+=1) {
//success code
}
}, function(error) {
console.log("Failed",error.type,error.message);
});
We must always add a catch() , otherwise promises will silently fail. In this case, if thePromise is rejected, the execution jumps directly to the catch() method. You can add the catch() method in the middle of two then() methods, but you will not be able to break the chain when something bad happens.
all() will reject immediately upon any of the input promises rejecting. In comparison, the promise returned by Promise. allSettled() will wait for all input promises to complete, regardless of whether or not one rejects.
race() , which returns the first settled value (either fulfillment or rejection), this method returns the first fulfilled value.
You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function. Copied!
The solution suggested by Interrobang is good (minus the bug) but if you dislike having decorators affect every single promise in your code you can get something similar to allSettled like this instead:
var suppress = function(x) { return x.catch(function(){}); }
$q.all(promises.map(suppress)).then(function(coords) {
for (var j = 0; j < coords.length ; j+=1) {
//coords[j] contains the coords on success or is undefined on failure
}
});
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