javascript - Angular's $q.reject() vs deferred.reject() -
i'm trying handle on angular $q service , related objects , apis. when @ objects in console see:
var deferred = $q.defer() ...(and console inspection)... $q: object {defer: function, reject: function, when: function, all: function} deferred: object {resolve: function, reject: function, notify: function, promise: object} deferred.promise: object {then: function, catch: function, finally: function} it raises few questions:
- what's difference between
$q.reject(),deferred.reject()? when use each? - what's relationship between
errorfnindeferred.promise.then(successfn, errorfn),catchfnindeferred.promise.catch(catchfn)? - if have bunch of nested promises , error occurs, outermost
catch()function called? if 1 of nested promises has catch function defined? catch prevent outermost catch executing?
thanks.
1) $q.reject() shortcut create deferred , reject immediately; use in errorfn if can't handle error.
2) nothing, promise.catch(errorfn) syntactic sugar promise.then(null, errorfn), success , error methods of $http service, can write code following:
promise. then(function(result){ // handle success return result; }, function errorhandler1(error){ // handle error, if separate catch in chain. }).catch(function errorhandler2(error){ // handle errors errorhandler1 }); 3) $q.reject can come in handy:
promise. catch(function(error){ //decide can't handle error return $q.reject(error); //this forwards error next error handler; }).catch(function(error){ // here may handle error or reject again. return 'an error occurred'; //now other errorfn in promise chain won't called, // successfn calls will. }).catch(function(error){ // never called because previous catch handles errors. }).then(function(result){ //this called either result of promise if successful, or //'an error occured' if wasn't });
Comments
Post a Comment