Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reject $http promise on success

I have a function that that returns a promise of an $http GET (the promise success/error is handled by the invoker). What I need is, given certain conditions and even though the $http is successful, to return an error (the invoker would catch this condition as a rejected promise).

In this plunk, I tried to return $q.reject() but this doesn't work.

http://plnkr.co/edit/iC3Wb1PBUFrXgPbTJyU0?p=preview

This is the JavaScript:

app.controller("ctrl", function($scope, $http) {
  var getUrl = function() {
    var config = {
      method: 'GET',
      url: 'some.txt'
    };
    var x = 1; // if x == 1 the http should fail
    return $http(config).success(function(response, status, headers, config) {
      console.log(response);
      if (x == 1) return $q.reject('error');
    }).error(function(data, status, headers, config) {});
  };
  var init = function() {
    var promise = getUrl();
    promise.then(function() {
      alert('OK');
    }, function() {
      alert('error');
    });
  };
  init();
});

Any ideas?

like image 237
ps0604 Avatar asked Jan 21 '15 20:01

ps0604


People also ask

Can you reject a resolved Promise?

A Promise executor should call only one resolve or one reject . Once one state is changed (pending => fulfilled or pending => rejected), that's all. Any further calls to resolve or reject will be ignored.

What happens when Promise is rejected?

If the Promise rejects, the second function in your first . then() will get called with the rejected value, and whatever value it returns will become a new resolved Promise which passes into the first function of your second then. Catch is never called here either.

How do you handle rejection promises?

We must always add a catch() , otherwise promises will silently fail. In this case, if thePromise is rejected, the execution jumps directly to the catch() method. You can add the catch() method in the middle of two then() methods, but you will not be able to break the chain when something bad happens.

What happens if you don't reject a Promise resolve?

A promise is just an object with properties in Javascript. There's no magic to it. So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else. This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.


1 Answers

$http.success() and error() are convenience shortcuts that are not 100% compliant with promises. Use vanilla promise then instead:

$http(config).then(function(response){return $q.reject}, function onError(reason){})

updated plunker

like image 172
Mykola Gurov Avatar answered Sep 25 '22 09:09

Mykola Gurov