Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make $q.all fail silently when one promise is rejected

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);
      });
like image 308
Tom Avatar asked Sep 02 '14 19:09

Tom


People also ask

How do you handle reject promises?

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.

Does promise all wait for all promises?

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.

What function will return as soon as the first promise is either fulfilled or rejected?

race() , which returns the first settled value (either fulfillment or rejection), this method returns the first fulfilled value.

How do you wait for the promise to complete?

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!


1 Answers

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
      }
});
like image 121
Benjamin Gruenbaum Avatar answered Sep 23 '22 19:09

Benjamin Gruenbaum