1

Can someone explain why the second promise returned by then function is resolved? It looks like Angular JS bug in its Promises implementation. According to the documentation here the second promise should also have been rejected.

// Code goes here
var myMod = angular.module("myMod", []);
myMod.controller('bodyCtrl', function($scope, $timeout, $q) {
    var deferred = $q.defer();
    deferred.promise.then(function(d) {
      console.log("success called");
      return d;
    }, function(d) {
      console.log("failure called");
      return d;
    })
    .then(function(d) {
      console.log("success called2");
      return d;
    }, function(d) {
      console.log("failure called2");
      return d;
    });
    
    $timeout(function() {
      deferred.reject();
    }, 2 * 1000);
});
<!DOCTYPE html>
<html ng-app="myMod">

  <head>
    <script src="https://code.angularjs.org/1.5.8/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="bodyCtrl">
    <h1>Hello Plunker!</h1>
  </body>

</html>
Sai Dubbaka
  • 621
  • 7
  • 11

2 Answers2

2

This is by design. It occurs because by providing the promise with an errorCallback, you're actually handling/resolving/catching the rejection (just as if you were catching an exception in a try...catch block). If you remove the first errorCallback function, you should be seeing failure called2 in the developer console instead, or if you in the first callback throw a new exception.

Nikolaj Dam Larsen
  • 5,455
  • 4
  • 32
  • 45
2

As @Nikolaj Dam Larsen and @georgeawg says, your problem is that in your errorCallback() you aren't throwing the exception. See the following example (PLUNKER)...

function bodyCtrl($timeout, $q){
    deferred.promise
    .then(function(d) { //Promise 1
        console.log("success called");
        return d;
    }, function(e) {
        console.log("failure called");
        throw e; //Throw instead return
    })
    .then(function(d) { //Promise 2
        console.log("success called2");
        return d;
    }, function(e) {
        console.log("failure called2");
        throw e; //Throw instead return
    });

    $timeout(function() {
        deferred.reject("Custom Rejected: " + new Date());
    }, 2000);
}
The.Bear
  • 5,621
  • 2
  • 27
  • 33
  • Also check this post to understand better http://stackoverflow.com/questions/23559341/using-success-error-finally-catch-with-promises-in-angularjs – The.Bear Mar 26 '17 at 23:20