$q promise error callback chains

Steven Wexler picture Steven Wexler · Oct 18, 2014 · Viewed 11.9k times · Source

In the following code snippet error 1 and success 2 will be logged. How can I can I propagate error callbacks being invoked rather than the success callbacks being invoked if the original deferred is rejected.

Answer

Chandermani picture Chandermani · Oct 18, 2014

Error is propagate by returning $q.reject in the error callback

    var deferred = $q.defer();
      deferred.reject();

      deferred.promise
          .then(
              /*success*/function () { console.log("success 1"); },
              /*error*/function () { console.log("error 1"); return $q.reject('error 1')})
          .then(
              /*success*/function () { console.log("success 2"); },
              /*error*/function () { console.log("error 2"); });
});