简体   繁体   English

成功时拒绝$ http承诺

[英]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). 我有一个函数,它返回$ http GET的承诺(承诺成功/错误由调用者处理)。 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). 我需要的是,在某些条件下,即使$ http成功,也要返回一个错误(调用者将这个条件视为被拒绝的承诺)。

In this plunk, I tried to return $q.reject() but this doesn't work. 在这个插件中,我试图返回$ q.reject()但这不起作用。

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

This is the JavaScript: 这是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? 有任何想法吗?

$http.success() and error() are convenience shortcuts that are not 100% compliant with promises. $http.success()error()是与promises不完全兼容的便捷快捷方式。 Use vanilla promise then instead: then使用香草诺言:

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

updated plunker 更新的plunker

Try this: http://plnkr.co/edit/hTNFjXXDfqQ7e7jvNMtg?p=preview 试试这个: http//plnkr.co/edit/hTNFjXXDfqQ7e7jvNMtg?p = preview

You return a deferred promise of your own and resolve/reject is on will 您返回自己的延期承诺,并随意解决/拒绝

 var defer = $q.defer();


          $http(config)
              .success(function (response, status, headers, config) {
                  console.log(response);

                  if (x == 1)
                       defer.reject('error');
                 else
                  defer.resolve(response);

              })
                .error(function (data, status, headers, config) {
              });

              return defer.promise;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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