$ http承诺总是回归原始承诺?

时间:2015-03-13 03:21:17

标签: javascript angularjs angular-promise

如果这不是一个好问题,我道歉,但这让我感到困惑。

我尝试从工厂内的$http.post()返回特定数据,但似乎$ http始终返回原始承诺。我希望避免.success和.error,因为他们可能在v1.5中贬值。鉴于工厂可能会做其他事情,比如localStorage等中的set items,我不想直接返回$ http.post()。

无论如何,以下是从角度$ http承诺中返回特定数据的最佳方法吗?

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;
}

2 个答案:

答案 0 :(得分:1)

您无需创建deferred对象。相反,您只需返回$http.post的结果即可。 $ http.post返回一个碰巧有两个额外方法(成功和失败)的承诺。

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,其中解释了如何通过承诺链传播数据和拒绝原因。

答案 1 :(得分:0)

我会将错误响应写成'然后'方法(我的例子如下)。这样,只有在$ 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() - 意味着如果在promise链中出现任何问题,它将被调用。因此,catch()最有可能在几个承诺结束时使用。例如,像这样的东西

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'

”部分