2

I want to do the following, i have a controller like this:

  dashboardService.getDashboardStateLakes().then(function (result) {
            if (result) {
                dosomething();
        }, function (err) {
            //TODO: handle error;
            //alert(err);
            throw new Error(err);
        });

        // populate dashboard lakes status (left upper of the screen)
        dashboardService.getDashboardLakesStatus().then(function (result) {
            if (result) {
                dosomething();
            }
        }, function (err) {
            //alert(err);
            //throw new Error(err);
        });

and in the service it's doing like this:

 this.getDashboardLakesStatus = function () {
        var deffered = $q.defer();
        $http.get(api.GET_dashboardLakesStatus)
            .success(function (result) {
                //logic
                deffered.resolve(result);
            })
             .error(function (data, status) {
                //logic
                deffered.reject(status);
        return deffered.promise;
    };

Now all i want is to do something when both the ajax calls are finished, but the problem is, sometimes, a 401 is coming back (deliberately) and $q all stops when an error occurs...what is my other option?

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
totothegreat
  • 1,633
  • 4
  • 27
  • 59

1 Answers1

3

Promise exception handling is similar to try/catch in synchronous code. You can make the promise resolve by recovering it from bad state:

$http.get(api.GET_dashboardLakesStatus).catch(function(e){ });// always resolved

Take note that the result of this get call will either be the actual response or undefined if there was an error. This will let you $q.all several of these calls even if some of them fail.

Also, note you have the deferred anti pattern. You don't have to create a deferred when working with an API that already returns promises. Consider using .then and .catch in favor of .success and .error while you're at it.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504