Angularjs promise rejection chaining

前端 未结 2 943
刺人心
刺人心 2020-12-24 12:15

I need to create chained promises:

var deferred = $q.defer();
$timeout(function() {
    deferred.reject({result: \'errror\'});
}, 3000);
deferred.promise.the         


        
相关标签:
2条回答
  • 2020-12-24 12:50

    And what the reason why it is done. In which case, the current behavior can be useful?

    It can be useful when in errorHandler you could try to repair error state and resolve promise somehow.

    var retriesCount = 0;
    
    function doWork()
    {
        return $http.post('url')
            .then(function(response){
                // check success-property of returned data
                if(response.data.success)
                    // just unwrap data from response, may be do some other manipulations
                    return response.data;
                else
                    // reject with error
                    return $q.reject('some error occured');
            })
            .catch(function(reason){
                if(retriesCount++ < 3)
                    // some error, let me try to recover myself once again
                    return doWork();
                else
                    // mission failed... finally reject
                    return $q.reject(reason);
            });
    }
    
    
    doWork().then(console.log, console.error);
    
    0 讨论(0)
  • 2020-12-24 13:01

    Late to the party, but as I am here;

    I prefer to use the $http error for its native error handling, rather than returning a success via a 200 and an error status in the response.

    printing 400 or 500 errors in the console is not an issue, if you are debugging you see them if not you don't.

    angular.module('workModule', [])
    
    // work provider handles all api calls to get work
    .service('workProvider', ['$http', '$q', function($http, $q) {
    
        var endpoint = '/api/v1/work/';
    
        this.Get = function(){
            // return the promise, and use 404, 500, etc for errors on the server
            return $http.get(endpoint);
        };
    
    }])
    
    .controller('workController', ['workProvider', function('workProvider'){
    
        workProvider.Get().then(
            function(response){ // success
                console.log(response.data);
            },
            function(response){ // error
                 console.log(response.data);           
            }
        )
    
    }])
    
    0 讨论(0)
提交回复
热议问题