简体   繁体   中英

Rejecting Angular $http promise

I need to reject an $http promise call in the success/then function. I can see 2 options: 1) thrown an error - this garbages up the console and 2) use separate defer call and reject that. Is there a cleaner/more concise way? I have a feeling I am overlooking something obvious.

Error:

return $http.get(url}.then(function(r) {
  throw new Error('Booh');
});

With $q:

var deferred = $q.defer();
$http.get(url}.then(function(r) {
   deferred.reject("Booh");
});
return deferred.promise;

Try this:

function myfunction()
{
    return $http.post('url')
        .then(function(response){
            // check success-property of returned data
            if(response.data === 'Something you dont want')
                return $q.reject('some error occured');
            else{
                return $q.resolve(response.data);
            }
        })
}

As $http is a modified promise do something like :

var deferred = $q.defer();

$http.get(url).success(function(r) {
   if(r != 'your criteria')
       deferred.reject("Booh");
   else
       deferred.resolve("Baah");
}).error(function(){
   deferred.reject("Beeh");
});

return deferred.promise

You can use de reject method of the $q service to immetiately forward to the next error section, something like:

var deferred = $q.defer();

$http.get(url}.success(function(r) {
     deferred.reject();
}).error(function(){
   // do something
});

When success q.reject will forward to the error and do something...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM