Angular error not thrown from promise finally block

785 views Asked by At

For some reason I dont see any errors (like syntax error) when they appear inside 'finally' block of a promise. Why is that?

angular.module('App', [])
  .controller('AppCtrl', function(TestService) {

    TestService.outerMethod().then(function() {
      console.log('Success')
    }, function(error) {
      console.error('Error')
    })

  })

.service('TestService', function($q) {

  this.outerMethod = outerMethod;

  function innerMethod() {
    var deferred = $q.defer();
    deferred.resolve();
    return deferred.promise;
  }

  function outerMethod() {

    var deferred = $q.defer();

    // syntaxErrorVisible

    innerMethod().finally(function() {

      // syntaxErrorNotVisible
      deferred.resolve();

    });

    return deferred.promise;
  }

})

;

Codepen: http://codepen.io/anon/pen/vOJGpG

The problem is that, when we uncomment those comments, that occur syntax errors, we wont wee any errors (in browser console) when errors is placed inside 'finally' block of this code.

Expecting syntax error but not shown Showing error as expected

2

There are 2 answers

0
CodingIntrigue On

The problem is the way you return the promise:

return deferred.promise

On this line you just returned the original promise. Your caller knows nothing about the finally attached to it. In order to keep the chain, you need to return the promise returned by finally:

function outerMethod() {

    var deferred = $q.defer();

    // syntaxErrorVisible

    return innerMethod().finally(function() {

      syntaxErrorNotVisible
      deferred.resolve();

    });
}

Updated Pen

0
Oguzhan On

I tried to edit it look better of what your trying to do. its not tested but should work.

.service('TestService', function($q) {


  this.innerMethod = function() {
    var deferred = $q.defer();
    deferred.resolve();
    return deferred.promise;   }



this.outerMethod = function(){  var deferred1 = $q.defer();

    this.innerMethod().then(
        function(success){
            deferred1.resolve("resolved");
    },
    function(error){

    })

} })
  • Here is the q library that would help you understand how q promise work indeed