$http 承诺总是 returns 原始承诺?

$http promise always returns original promise?

如果这不是一个好问题,我深表歉意,但这让我有点困惑。

我正在尝试 return 来自工厂内 $http.post() 的特定数据,但是 $http 似乎总是 return 原始承诺。我希望避免 .success 和 .error,因为它们可能在 v1.5 中贬值。鉴于工厂可能会做其他事情,例如在 localStorage 中设置项目等,我不想直接 return $http.post()。

无论如何,以下是从 angular $http promise return 特定数据的最佳方式吗?

function login (email, password) {
  var deferred = $q.defer();

  $http.post('/api/auth', {
    email: email,
    password: password
  })
    .then(function (data) {
      return deferred.resolve('success');
    })
    .catch(function (data) {
      return deferred.reject('fail');
    });

  return deferred.promise;
}

您不需要创建 deferred 对象。相反,您可以 return 来自 $http.post 的结果。 $http.post return 是一个恰好有两个额外方法(成功和失败)的承诺。

function login(email, password) {
  return $http.post('/api/auth', {
    email: email,
    password: password
  })
  .then(function (data) {
    var newData = translateData(data);
    //now the data will be passed to the next promise
    return newData;
  })
  .catch(function (reason) {
    /*do stuff with failure*/
    //Now the rejection reason will be propagated to the next promise
    return $q.reject(reason);
  });
}

login()
  //You should get your data here.
  .then(function (data) { console.log(data); }) 
  .catch(function (reason) { console.log(reason); });

您可能有兴趣阅读此 blog post,其中解释了如何通过承诺链传播数据和拒绝原因。

我会用错误响应编写它作为 'then' 方法的第二次回调(我在下面的示例)。这样,只有在 $http 请求出错时才会调用错误回调。

function login (email, password) { 
   var deferred = $q.defer();
   $http.post('/api/auth', {
     email: email,
     password: password
   })
   .then(function (data) {
     return deferred.resolve(data);
   }, function (message) {
     return deferred.reject(message);
   });
   return deferred.promise;
}

您完成它的方式 - 使用 catch() - 意味着如果承诺链中出现任何错误,它将被调用。因此,catch() 最有可能在多个 promise 的末尾使用。例如,像这样的东西

CustomerService.login(email, password)
   .then(getUserData)
   .then(setUpAccount)
   .catch($log.error);

See this great post, which explains it far better than I did

此外,请查看 promises 上的文档,'The Promise API'

上的部分