用角度服务链接http.get承诺

时间:2017-05-16 20:47:51

标签: angularjs angular-promise angularjs-http

这是一个不好的方法吗?我基本上链接了promises,每次成功从服务器返回,都会启动一个新的http.get()以获取更多信息,但不会出现错误。如果它导致errorCallback,不再需要http.get();

$http.get(...).then(function() {
  $http.get(...).then(function(){ 
      $http.get(...).then(function(){}, function(){}), 
   function(){}); }, 
mainErrorCallback);

如果它不是" $ http.get()"它会有所作为吗?它确实" ViewsService.loadViews()"在

里面
$http.get(...).then( function() { ViewsService.loadViews(); }, function(){ console.log("error"); }). 

编辑:这就是我的意思,同步......似乎它有效,但代码需要清理/效率才能看起来更整洁:

http://jsfiddle.net/4n9fao9q/6/

(延迟的http请求):http://jsfiddle.net/4n9fao9q/26

2 个答案:

答案 0 :(得分:2)

$http.get(...).then((res) => {
  //res has data from first http
  return $http.get(...);
}).then((res) => {
  //res has data from second http
  return $http.get(...);
}).then((res) => {
  //res has data from third http
}).catch((err) => {
  //exploded
});

我认为更清洁。你可以用任何返回promise的函数替换$ http.get。如果ViewsService.loadViews()返回一个promise,你可以使用它。

如评论中所述。

...
ViewsService.loadViews = function() {
  //returns a promise
  return $http.get(...);
}

OR

ViewsService.loadViews = function() {
  return new Promise((resolve, reject) => {
    $http.get(...).then((result) => {
      //whatever
      return resolve();
    })
  })
  return $http.get(...);
}

使用loadViews的任何选项,您可以执行ViewsService.loadViers.then(etc)

答案 1 :(得分:1)

这是一个不好的方法吗?

  • 效率

除非您使用第一个请求的响应作为以下请求的输入,否则不是 这是一种非常有效的方法,因为每个请求都会被阻止,直到前一个请求返回为止。一个更好的 方法是使用$.all($http.get(...),$http.get(...))

  • 风格

嵌套调用(the pyramid of doom)很难阅读。由于每个呼叫都有相同的故障响应,您可以将这些呼叫链接起来。例如

`$http.get(..).then
 ($http.get(..)).then(
 ($http.get(..)).catch(errHander)`
相关问题